-
-
Save gbajaj/3bd426acf49eba7bd601500a2807ec9a to your computer and use it in GitHub Desktop.
flatMapLatest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun <T, R> Flow<T>.flatMapLatest(transform: suspend (T) -> Flow<R>): Flow<R> = flow { | |
// This coroutineScope is key to managing cancellation of the inner flow | |
coroutineScope { | |
var previousJob: Job? = null | |
collect { value -> | |
// Cancel any ongoing inner flow collection | |
previousJob?.cancelAndJoin() | |
// Launch new inner flow collector in a new coroutine | |
previousJob = launch { | |
transform(value).collect { innerValue -> | |
emit(innerValue) // Emit downstream | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment