Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
LiveData as Flow of Kotlin Coroutines
fun <T> LiveData<T>.asFlow() = flowViaChannel<T?> {
it.send(value)
val observer = Observer<T> { t -> it.offer(t) }
observeForever(observer)
it.invokeOnClose {
removeObserver(observer)
}
}
val text = MutableLiveData<String>()
fun main() {
launch(Dispatchers.Main) {
text.asFlow()
.filterNot {
it.isNullOrBlank()
}
.collect {
println(it)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment