Obviously this is an anti-pattern, but how would o...
# coroutines
z
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
Just use
produceIn
👍 1
z
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.
👍 1