Skip to content

Instantly share code, notes, and snippets.

@FireZenk
Created February 25, 2020 12:14
Show Gist options
  • Save FireZenk/17c02cc4b27aa4d7bd9a4279355c5aff to your computer and use it in GitHub Desktop.
Save FireZenk/17c02cc4b27aa4d7bd9a4279355c5aff to your computer and use it in GitHub Desktop.
MVI Android + Rxjava2
open class Action
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import io.reactivex.disposables.CompositeDisposable
abstract class MVIViewModel<A: Action, S: State>(val store: Store = Store()): ViewModel() {
private val state: MutableLiveData<S> = MutableLiveData()
protected val disposables: CompositeDisposable = CompositeDisposable()
abstract infix fun reduce(action: A)
fun S.pushState() {
store.add { this }
state.value = this
}
fun pullState(owner: LifecycleOwner, observer: (S) -> Unit) {
state.observe(owner, Observer { observer(it) })
}
fun dispose() {
store.clear()
disposables.clear()
}
}
open class State
class Store {
private val states: MutableList<State> = mutableListOf()
val frozenStates: List<State>
get() = states.toList()
internal fun add(function: () -> State) {
states.add(function())
}
internal fun clear() = states.clear()
inline fun <reified S> provideLast(): S? = frozenStates.findLast { it is S } as S?
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment