Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert BroadcastChannel(via Kotlin coroutines) to LiveData
package your.awesome.domain
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.channels.ConflatedBroadcastChannel
import kotlinx.coroutines.experimental.channels.ReceiveChannel
import kotlinx.coroutines.experimental.channels.consumeEach
import kotlinx.coroutines.experimental.launch
fun <T> ConflatedBroadcastChannel<T>.toLiveData() : LiveData<T> {
val channel = this
val liveData = object : MutableLiveData<T>() {
private var subscription: ReceiveChannel<T>? = null
override fun onActive() {
super.onActive()
val ld = this
// Receive in UI thread
launch(UI) {
val receiveChannel = channel.openSubscription()
subscription = channel.openSubscription()
receiveChannel.consumeEach {
ld.postValue(it)
}
}
// Emit latest value when on active
val value = channel.valueOrNull
if (value != null) {
ld.postValue(value)
}
}
override fun onInactive() {
subscription?.cancel()
subscription = null
super.onInactive()
}
}
return liveData
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment