Skip to content

Instantly share code, notes, and snippets.

@bopbi
Created January 25, 2019 07:57
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 bopbi/5db55f7b34c68bd742370fdc4a326f43 to your computer and use it in GitHub Desktop.
Save bopbi/5db55f7b34c68bd742370fdc4a326f43 to your computer and use it in GitHub Desktop.
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
fun main() {
View()
}
class View {
init {
val viewModel = ViewModel()
val disposable = viewModel.getState().subscribe {
println(it)
}
viewModel.login()
viewModel.loading()
viewModel.error()
// viewModel.loading()
disposable.dispose()
viewModel.loading()
println()
viewModel.getState().subscribe {
println(it)
}
}
}
class ViewModel {
val behaviorSubject = BehaviorSubject.create<String>()
val behaviorSubject2 = BehaviorSubject.create<String>()
fun login() {
behaviorSubject.onNext("Login")
}
fun loading() {
behaviorSubject.onNext("Loading")
}
fun error() {
behaviorSubject.onNext("Error")
}
fun getState(): Observable<String> {
return behaviorSubject.scan { oldState, newState ->
var state = newState
if ((oldState == "Error") && (newState == "Loading")) {
state = "Confused"
}
state
}.replay(1).autoConnect(0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment