Created
June 7, 2018 07:01
-
-
Save amay077/478db922b3e080c045a8e5f3515bd665 to your computer and use it in GitHub Desktop.
Convert BroadcastChannel(via Kotlin coroutines) to LiveData
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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