Skip to content

Instantly share code, notes, and snippets.

@amay077
Created June 7, 2018 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amay077/478db922b3e080c045a8e5f3515bd665 to your computer and use it in GitHub Desktop.
Save amay077/478db922b3e080c045a8e5f3515bd665 to your computer and use it in GitHub Desktop.
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