Hi, I want to tranform a flow to a disposable/clos...
# coroutines
p
Hi, I want to tranform a flow to a disposable/closeable value and automatically close/dispose each transformed value as soon as a new value is emitted or the flow completes. I have come up with the following implementation of this behavior:
Copy code
@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?
n
Are you aware that the code using your disposable item may not be done with it.
flatMapLatest
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.