https://kotlinlang.org logo
#coroutines
Title
# coroutines
l

Lukas Lechner

08/21/2022, 8:22 AM
Are there any use cases for using Channels in Android Development, or are you exclusively using Flows in your apps?
l

luke_c

08/21/2022, 9:32 AM
We're using channels for one time events, as a replacement for SingleLiveEvent
SharedFlow isn't a viable replacement as if an event is emitted when there's no subscribers it will be dropped
l

Lukas Lechner

08/21/2022, 10:24 AM
@luke_c Hmm, but Google says we shouldn't use channels for one time events: https://medium.com/androiddevelopers/viewmodel-one-off-event-antipatterns-16a1da869b95
l

luke_c

08/21/2022, 10:28 AM
In practice it's very unlikely it's going to be a problem... But I agree with the principal of handling events as state like the article mentions
l

Lukas Lechner

08/21/2022, 10:56 AM
Okay, and as far as I understood, events can only stay unprocessed if
send()
and/or
collect()
are called on a different Dispatcher than
Dispatchers.Main.immediate
, which shouldn't be the case that often since
lifecycleScope
and
viewModelScope
use this dispatcher by default, right?
l

luke_c

08/21/2022, 11:18 AM
Yes that's my understanding. It's important you use a buffered Channel so any events sent when there are no subscribers are buffered and not dropped
l

Lukas Lechner

08/21/2022, 11:28 AM
Okay, by default they have a capacity of 0, so we have to set it to a value >0, correct?
l

luke_c

08/21/2022, 11:35 AM
We use Channel.BUFFERED One caveat is that Channels have a fan out behaviour, so it's not reliable if you need multiple observers, but that's generally not a problem for most people and the same limitation that SingleLiveEvent has