Last active
June 20, 2020 02:36
-
-
Save ursusursus/11ec56dbf6cdfaba12c59409147b7584 to your computer and use it in GitHub Desktop.
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
class Presenter<S>(state: S) { | |
private val _state = BehaviorRelay.createDefault(state) | |
val state: Observable get() = _state | |
protected fun setState(reducer: S.() -> S) { | |
// Enforce main thread to avoid synchronization | |
// | |
val oldState = stateRelay.value!! | |
stateRelay.accept(oldState.reducer()) | |
} | |
protected fun state(): S { | |
return stateRelay.value!! | |
} | |
} | |
class FooPresenter(initialState: State, repository: Repository) : Presenter(initialState) { | |
override fun init() { | |
repository.foo | |
.subscribe { | |
setState { | |
copy(foo = it) | |
} | |
} | |
repository.bar | |
.subscribe { | |
setState { | |
copy(bar = it) | |
} | |
} | |
} | |
fun someClick() { | |
val state = state() | |
// Here I can read state synochronously, which is a plus | |
// call navigator interfaces, and what not | |
// Or simple return if in invalid case (and we cannot bother to do a full finite state machine) | |
// Or create a new state | |
setState { | |
copy(counter = counter + 1) | |
} | |
} | |
data class State(foo: Foo? = null, bar: Bar? = null, val counter: Int = 0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment