LiveDataTestUtil.kt 732 B

123456789101112131415161718192021222324252627
  1. package com.sduduzog.slimlauncher
  2. import android.arch.lifecycle.LiveData
  3. import android.arch.lifecycle.Observer
  4. import java.util.concurrent.CountDownLatch
  5. import java.util.concurrent.TimeUnit
  6. object LiveDataTestUtil {
  7. @Throws(InterruptedException::class)
  8. fun <T> getValue(liveData: LiveData<T>): T {
  9. val data = arrayOfNulls<Any>(1)
  10. val latch = CountDownLatch(1)
  11. val observer = object : Observer<T> {
  12. override fun onChanged(o: T?) {
  13. data[0] = o
  14. latch.countDown()
  15. liveData.removeObserver(this)
  16. }
  17. }
  18. liveData.observeForever(observer)
  19. latch.await(2, TimeUnit.SECONDS)
  20. return data[0] as T
  21. }
  22. }