Skip to content

Instantly share code, notes, and snippets.

@gbajaj
Created July 2, 2025 05:12
Show Gist options
  • Save gbajaj/3bd426acf49eba7bd601500a2807ec9a to your computer and use it in GitHub Desktop.
Save gbajaj/3bd426acf49eba7bd601500a2807ec9a to your computer and use it in GitHub Desktop.
flatMapLatest
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