Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstrates an Observer for LiveData to be used during unit testing.
/**
* This defines the contract for communicating with some data source to request profile information.
*/
interface ProfileRepository {
fun fetchProfile(userId: String): Single<User>
}
/**
* Our profile view can be in one of three states: loading, successful data request, or an error requesting data.
*/
data class ProfileViewState(
val loading: Boolean,
val data: User?,
val error: Throwable?
)
/**
* This TestObserver keeps track of all events emitted to a
* LiveData so that our unit tests can validate all of the expected emissions
* occurred.
*/
class TestObserver<T> : Observer<T> {
var observedValues: MutableList<T> = mutableListOf()
override fun onChanged(t: T) {
observedValues.add(t)
}
}
fun <T> LiveData<T>.testObserver() = TestObserver<T>().also {
observeForever(it)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.