Created
July 6, 2017 16:59
-
-
Save ZakTaccardi/9c2d1d2fac5bfc55405bdc1b1d2e36d3 to your computer and use it in GitHub Desktop.
Exposing Information: Observing Events vs State (in Rx)
This file contains hidden or 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
class UserRepository{ | |
// note: hot observables that do not replay missed events | |
fun logins(): Observable<User> | |
fun logouts(): Observable<Unit> | |
} | |
/** | |
* An abstract user with two implementations: | |
* "LoggedIn" and "Logged out" | |
*/ | |
sealed class User { | |
// note: this represents a logged in user, not a log in event. | |
data class LoggedIn(val name: String) : User() | |
object LoggedOut : User() | |
} | |
class UserRepository { | |
// emits the state of the user over time (as it changes) | |
fun userStates() : Observable<User> | |
} | |
class MainActivity : Activity() { | |
override fun onStart() { | |
userRepository.userStates() | |
.filter { user: User -> user is User.LoggedOut } | |
.map { user: User -> user as User.LoggedOut } | |
.subscribe { navigateToLoginScreen() } | |
} | |
} | |
User.LoggedOut //current state is emitted upon subscription | |
User.LoggedIn("Zak") | |
User.LoggedIn("Zak Taccardi") | |
User.LoggedOut | |
val userStates : Observable<User> = userRepository.userStates() | |
userStates | |
.distinctUntilChanged { | |
old: User, new: User -> old.javaClass == new.javaClass | |
} | |
// distinctUntilChange() emits first value by default. | |
// Skip it, because we need at least 2 to do the comparison | |
.skip(1) | |
.map { user: User -> | |
if (user is User.LoggedIn) { | |
// a user just logged in! | |
"${user.name} logged in!" | |
} else { | |
// a user just logged out! | |
"Logged out!" | |
} | |
} | |
.subscribe { log -> println(log) } | |
// output: | |
// Zak logged in! | |
// Logged out! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment