Skip to content

Instantly share code, notes, and snippets.

@ursusursus
Last active June 20, 2020 02:36
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 ursusursus/11ec56dbf6cdfaba12c59409147b7584 to your computer and use it in GitHub Desktop.
Save ursusursus/11ec56dbf6cdfaba12c59409147b7584 to your computer and use it in GitHub Desktop.
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