Last active
January 14, 2019 22:48
-
-
Save westonal/da1c68c4c77984bdfd2de29faee4acf6 to your computer and use it in GitHub Desktop.
Get data from LiveData via coroutines, based on https://github.com/googlesamples/android-sunflower/blob/master/app/src/androidTest/java/com/google/samples/apps/sunflower/utilities/LiveDataTestUtil.kt
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 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