Skip to content

Instantly share code, notes, and snippets.

@chibatching
Last active April 19, 2019 05:50
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 chibatching/9fdd23d0d41980980a1c1af2e1803e01 to your computer and use it in GitHub Desktop.
Save chibatching/9fdd23d0d41980980a1c1af2e1803e01 to your computer and use it in GitHub Desktop.
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