Obviously this is an anti-pattern, but how would one go about converting a
Flow<T>
into a
ReceiveChannel<T>
?
I’ve tried the following so far, but it’s deadlocking
Copy code
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("You should be using Flows, not channels.")
fun <T> Flow<T>.collectAsReceiveChannel(scope: CoroutineScope): ReceiveChannel<T> {
val flow = this
val channel = Channel<T>()
val flowJob = scope.launch {
flow
.onEach { item -> channel.send(item) }
.collect()
}
channel.invokeOnClose {
flowJob.cancel()
}
return channel
}
l
louiscad
09/06/2019, 5:56 AM
Just use
produceIn
👍 1
z
Zach Klippenstein (he/him) [MOD]
09/06/2019, 5:31 PM
What Louis said – not only is it less code for you to write, it also plugs into channel operator fusion so can be more efficient.