Hi, I'm a bit confused when to use `LiveData`, `Ch...
# coroutines
l
Hi, I'm a bit confused when to use
LiveData
,
Channels
,
Flow
. I did some researches and if I got it right,
LiveData
is prefered in
ViewModel
because of it's lifecycle awareness and it runs in main thread while in data layer
Flow
is preferred. But what about
Channels
, where does it fit in? Or does
Flow
replace
Channels
in the long run?
r
Channel
is nowadays just a low-level primitive for coroutines synchronization. There are still cases not covered by
Flow
, but there are becoming less of them with time.
l
Sorry, but what means low-level?
z
Channels are basically an implementation of "blocking" queues (except they don't block, they suspend). If you need a blocking queue in a coroutine, use a channel. They're probably not the right tool for most other things though*. * This is technically only true once SharedFlow and friends get released, which will hopefully be soon.
👍 1
r
I mean in terms of abstraction level. Flow is more like a user-facing thing which would appear throughout your public API. Channels, on the other hand, would appear only internally, specifically when you implement some custom patterns of communication between your coroutines not supported otherwise.
l
Thanks for the detailed answer. When I'm in a data layer (i.e. a class which acts like a repository) and I want to expose a connection state (i.e. an enum CONNECTED, DISCONNECTED, ESTABLISHED) should I use a channel or a flow?
I guess Flow would better fit in here, right?
z
Yes,
StateFlow
would probably be the best fit.
l
ok nice