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

ahulyk

07/24/2019, 9:11 AM
Hi there 🙂 What is the best way to integrate Channels/Flow with LiveData ?
g

gildor

07/24/2019, 9:14 AM
There is no official adapter yet
But you can easily write simple ad-hoc implementation yourself
a

ahulyk

07/24/2019, 9:15 AM
Thanks 🙂
g

gildor

07/24/2019, 9:16 AM
for now you have to use ConflatedBroadcastChannel (or flow which uses conflated channel) to implement adapter for LiveData
t

tseisel

07/24/2019, 9:19 AM
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

gildor

07/24/2019, 9:20 AM
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

Joaquim Ley

07/24/2019, 9:24 AM
Hey if you figure out a working solution consider posting 😉
a

ahulyk

07/24/2019, 9:31 AM
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

gildor

07/24/2019, 9:33 AM
it will not work
this function will suspend until channel is closed which broke it main use case
a

ahulyk

07/24/2019, 10:22 AM
What is the best way to fix that? Passing Scope as parameter?
g

gildor

07/24/2019, 10:59 AM
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

Zach Klippenstein (he/him) [MOD]

07/24/2019, 6:08 PM
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
10 Views