Hi there :slightly_smiling_face: What is the best ...
# coroutines
a
Hi there 🙂 What is the best way to integrate Channels/Flow with LiveData ?
g
There is no official adapter yet
But you can easily write simple ad-hoc implementation yourself
a
Thanks 🙂
g
for now you have to use ConflatedBroadcastChannel (or flow which uses conflated channel) to implement adapter for LiveData
t
ConflatedBroadcastChannel
is the closest thing to
LiveData
. You could create a
LiveData
subclass that wraps a
ConflatedBroadcastChannel
. You can also use the
liveData
function from
androidx.lifecycle:lifecycle-livedata-ktx
: https://developer.android.com/topic/libraries/architecture/coroutines#livedata
g
You could create a
LiveData
subclass that wraps a
ConflatedBroadcastChannel
I would rather create adapter
LiveData.asFlow()
and
Flow.asLiveData()
than use inheritance
☝️ 1
j
Hey if you figure out a working solution consider posting 😉
a
Copy code
suspend fun <T> BroadcastChannel<T>.asLiveData(): LiveData<T> {
    val liveData = MutableLiveData<T>()
    consumeEach { value ->
        liveData.postValue(value)
    }
    return liveData
}
this shoud work - will test it later
g
it will not work
this function will suspend until channel is closed which broke it main use case
a
What is the best way to fix that? Passing Scope as parameter?
g
Something like:
Copy code
fun <T> BroadcastChannel<T>.consumeAsLiveData(scope: CoroutineScope): LiveData<T> {
    val liveData = MutableLiveData<T>()
    scope.launch { 
        consumeEach { 
            liveData.postValue(it)
        }
    }
    return liveData
}
👍 2
or even the same for ReceiveChannel
z
there is a
liveData
coroutine builder function that you can use for this too: https://developer.android.com/topic/libraries/architecture/coroutines#livedata
Copy code
fun <T> BroadcastChannel<T>.consumeAsLiveData(scope: CoroutineScope): LiveData<T> = liveData {
    consumeEach { 
        emit(it)
    }
}
💯 1