https://kotlinlang.org logo
#flow
Title
# flow
e

expensivebelly

03/01/2022, 7:14 PM
Any guide on how to migrate
Copy code
@ObsoleteCoroutinesApi
public fun <E> CoroutineScope.broadcast(
    context: CoroutineContext = EmptyCoroutineContext,
    capacity: Int = 1,
    start: CoroutineStart = CoroutineStart.LAZY,
    onCompletion: CompletionHandler? = null,
    @BuilderInference block: suspend ProducerScope<E>.() -> Unit
): BroadcastChannel<E>
to
SharedFlow
?
n

Nick Allen

03/01/2022, 10:50 PM
New code could look something like:
Copy code
channelFlow {
   send(fetchThis())
   send(fetchThat())
}.buffer(someCapacity).shareIn(scope, SharingStarted.Lazily)
`channelFlow`/`callbackFlow` are kinda the
Flow
equivalent of
produce
. buffering is handled with a separate call (before
shareIn
).
shareIn
is what allows multiple collectors to share the producing coroutine.`
👍 1
e

expensivebelly

03/02/2022, 7:43 PM
What if the original implementation was closing the channel? I'm going to assume you can't close that
channelFlow
in there?
n

Nick Allen

03/02/2022, 7:49 PM
channelFlow
terminates when the end of the lambda is reached. However,
shareIn
produces a
Flow
that never terminates. Check out the docs (https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/share-in.html) on dealing with errors and completion. Basically, if you want to forward errors/completion, you need to materialize them into items.