Skip to content

Instantly share code, notes, and snippets.

@AdamMc331
Last active June 11, 2020 01:20
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 AdamMc331/79067b6572f88cf0ff2b78880bdd9463 to your computer and use it in GitHub Desktop.
Save AdamMc331/79067b6572f88cf0ff2b78880bdd9463 to your computer and use it in GitHub Desktop.
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