Philipp Kleber
06/17/2022, 11:46 AM@OptIn(ExperimentalCoroutinesApi::class)
inline fun <T, S> Flow<T>.mapDisposable(
crossinline transform: suspend (value: T) -> S,
crossinline onDispose: (S) -> Unit
) : Flow<S> {
return flatMapLatest { value ->
callbackFlow {
val transformed: S = transform(value)
trySend(transformed)
awaitClose {
onDispose(transformed)
}
}
}
}
Is there a better or even a built-in way for achieving this?Nick Allen
06/17/2022, 9:06 PMflatMapLatest
uses a channel so the collector is in a different coroutine than the callbackFlow
lambda. Also, flatMapLatest
may cancel collecting from the Flow
but it has no effect on any coroutines running based on already emitted values.