Skip to content

Instantly share code, notes, and snippets.

@kiratheone
Forked from tinmegali/LiveData.ext.kt
Created October 29, 2018 14:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiratheone/82b8eb5a0bf4f4648b6353c722aaa9f8 to your computer and use it in GitHub Desktop.
Save kiratheone/82b8eb5a0bf4f4648b6353c722aaa9f8 to your computer and use it in GitHub Desktop.
Kotlin extension to allow Unit tests on Android LiveData
package com.tinmegali.daggerwithkotlin.room
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.Observer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
// Extension to allow unit tests on LiveData
// discussion on: https://stackoverflow.com/questions/44270688/unit-testing-room-and-livedata
fun <T> LiveData<T>.blockingObserve(): T? {
var value: T? = null
val latch = CountDownLatch(1)
val innerObserver = Observer<T> {
value = it
latch.countDown()
}
observeForever(innerObserver)
latch.await(2, TimeUnit.SECONDS)
return value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment