Last active
June 11, 2020 01:20
-
-
Save AdamMc331/79067b6572f88cf0ff2b78880bdd9463 to your computer and use it in GitHub Desktop.
Demonstrates an Observer for LiveData to be used during unit testing.
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
/** | |
* This defines the contract for communicating with some data source to request profile information. | |
*/ | |
interface ProfileRepository { | |
fun fetchProfile(userId: String): Single<User> | |
} |
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
/** | |
* 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 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
/** | |
* 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