Skip to content

Instantly share code, notes, and snippets.

@westonal
Last active January 14, 2019 22:48
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 westonal/da1c68c4c77984bdfd2de29faee4acf6 to your computer and use it in GitHub Desktop.
Save westonal/da1c68c4c77984bdfd2de29faee4acf6 to your computer and use it in GitHub Desktop.
package com.example
import androidx.lifecycle.LiveData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
fun <T> LiveData<T>.blockingGet(): T =
runBlocking {
val data = AtomicReference<T?>()
val latch = CountDownLatch(1)
val observe = { o: T ->
data.set(o)
latch.countDown()
}
withContext(Dispatchers.Main) {
this@blockingGet.observeForever(observe)
}
latch.await(2, TimeUnit.SECONDS)
withContext(Dispatchers.Main) {
this@blockingGet.removeObserver(observe)
}
data.get() ?: throw RuntimeException("Value was not recovered from LiveData in time.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment