Created
February 25, 2020 12:14
-
-
Save FireZenk/17c02cc4b27aa4d7bd9a4279355c5aff to your computer and use it in GitHub Desktop.
MVI Android + Rxjava2
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
open class Action |
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
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() | |
} | |
} |
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
open class State |
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 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