And the other way round, a `LiveData` as `Flow`: `...
# android
m
And the other way round, a
LiveData
as `Flow`:
Copy code
@UseExperimental(ExperimentalCoroutinesApi::class)
fun <Value> LiveData<Value>.asFlow() = channelFlow<Value> {
	val observer = Observer(this::offer)
	observeForever(observer)
	awaitClose { removeObserver(observer) }
}
d
Instead of
launch
and
send
, consider using
offer
.
m
Great thanks, updated 🙂
d
Also, you have to call
awaitClose
after
observeForever
. Otherwise the observer will be registered after the
Flow
closes/completes.
m
oh right, it will suspend there 😮 updated 🙂
a
Basically yes. More or less that is pending a future -ktx artifact release in androidx 🙂
🎉 4
l
Also, you probably want to use
conflate()
.
m
Hmm, `LiveData`’s
emit()
suspends until the value has actually been set. If I use
conflate()
for the other way round with
Flow
the behavior would be different, wouldn’t it?
I guess it’s already a problem because
channelFlow
is already buffered 🤔
Nevermind, I mixed it up. This is about getting a value out of
LiveData
, not into it 🙄
As I can’t edit the original message anymore here the updated version:
Copy code
@UseExperimental(ExperimentalCoroutinesApi::class)
fun <Value> LiveData<Value>.asFlow() = channelFlow<Value> {
    val observer = Observer(this::offer)
    observeForever(observer)
    awaitClose { removeObserver(observer) }
}.conflate()
👍 2