Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from LiveData synchronously?

For LiveData, is there something similar to blockingNext or blockingSingle in RxJava's Observable to get the value synchronously? if not, how can i achieve the same behavior?

like image 786
y.allam Avatar asked Apr 27 '18 20:04

y.allam


2 Answers

You can call getValue() to return the current value, if there is one. However, there is no "block until there is a value" option. Mostly, that is because LiveData is meant to be consumed on the main application thread, where indefinitely-blocking calls are to be avoided.

If you need "block until there is a value", use RxJava and ensure that you are observing on a background thread.

like image 50
CommonsWare Avatar answered Oct 24 '22 00:10

CommonsWare


With Kotlin coroutines

callbackFlow {
    val observer = Observer<Unit> {
        trySend(Unit)
    }
    MutableLiveData<Unit>().also {
        it.observeForever(observer)
        awaitClose {
            it.removeObserver(observer)
        }
    }
}.buffer(Channel.Factory.CONFLATED)
    .flowOn(Dispatchers.Main.immediate)
// e.g. single()
like image 23
Vlad Avatar answered Oct 24 '22 00:10

Vlad