Skip to content

Instantly share code, notes, and snippets.

@WendyYanto
Last active May 14, 2021 14:54
Show Gist options
  • Save WendyYanto/3046484f871467cda441b13e1e6ae82b to your computer and use it in GitHub Desktop.
Save WendyYanto/3046484f871467cda441b13e1e6ae82b to your computer and use it in GitHub Desktop.
class RxJavaUnitTest {
companion object {
private const val NAME = "John Doe"
private const val AGE = 20
private const val EMPTY = ""
}
@Test
fun getUserWithError() {
getUserId()
.flatMap(this::getUser)
.flatMap(this::saveUser)
.subscribe { user ->
if (user.hasError) {
println("user ID is invalid")
} else {
println(user)
}
}
}
private fun getUserId(): Observable<String> {
return Observable.fromCallable {
EMPTY
}
}
private fun getUser(id: String): Observable<User> {
if (id == EMPTY) {
val defaultUser = User(
id = EMPTY,
name = EMPTY,
age = -1,
hasError = true
)
return Observable.just(defaultUser)
}
val user = User(
id = id,
name = NAME,
age = AGE
)
return Observable.fromCallable { user }
}
private fun saveUser(user: User): Observable<User> {
if (user.hasError) {
return Observable.just(user)
}
// Perform save to user
return Observable.fromCallable { user }
}
}
data class User(
val id: String,
val name: String,
val age: Int,
var hasError: Boolean = false
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment