Created
September 23, 2019 08:37
-
-
Save BraisGabin/05a8b5de826e35f313367a1f8536f61e to your computer and use it in GitHub Desktop.
An implementation of MVI inspired by MVICore by Badoo
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
package com.b21 | |
import com.jakewharton.rxrelay2.PublishRelay | |
import com.jakewharton.rxrelay2.Relay | |
import io.reactivex.BackpressureStrategy | |
import io.reactivex.Flowable | |
import io.reactivex.functions.Consumer | |
import org.reactivestreams.Subscriber | |
/** | |
* ¡Qué bonito! | |
*/ | |
abstract class Feature<State, Wish, News> : Flowable<State>(), Consumer<Wish> { | |
abstract val state: State | |
abstract val news: Flowable<News> | |
} | |
typealias Actor<State, Action, Effect> = (State, Action) -> Flowable<Effect> | |
typealias PostProcessor<Action, Effect, State> = (Action, Effect, State) -> Action? | |
typealias NewsPublisher<Action, Effect, State, News> = (Action, Effect, State) -> News? | |
class BaseViewFeature<State, Wish : () -> Action, News, Effect : (State) -> State, Action>( | |
initialState: State, | |
bootstrapper: Flowable<Action> = Flowable.empty(), | |
private val actor: Actor<State, Action, Effect>, | |
private val postProcessor: PostProcessor<Action, Effect, State> = { _, _, _ -> null }, | |
private val newsPublisher: NewsPublisher<Action, Effect, State, News> = { _, _, _ -> null } | |
) : Feature<State, Wish, News>() { | |
private val actions: Relay<Action> = PublishRelay.create() | |
private val newsRelay: Relay<News> = PublishRelay.create() | |
private val states: Flowable<State> = actions | |
.toFlowable(BackpressureStrategy.BUFFER) | |
.startWith(bootstrapper) | |
.flatMap { action -> | |
actor(state, action) | |
.doOnNext { | |
//if (notInMain) CRASH! | |
} | |
} | |
.scan(initialState) { state, effect -> | |
effect(state) | |
} | |
.doOnNext { | |
state = it | |
} | |
.doOnNext { (action, effect, state) -> | |
val action2 = postProcessor(action, effect, state) | |
if (action2 != null) { | |
actions.accept(action2) | |
} | |
} | |
.doOnNext { (action, effect, state) -> | |
val news = newsPublisher(action, effect, state) | |
if (news != null) { | |
newsRelay.accept(news) | |
} | |
} | |
.replay(1) | |
.refCount() | |
override var state: State = initialState | |
private set | |
override val news: Flowable<News> = newsRelay.toFlowable(BackpressureStrategy.BUFFER) | |
override fun subscribeActual(s: Subscriber<in State>) { | |
states.subscribe(s) | |
} | |
override fun accept(wish: Wish) { | |
actions.accept(wish()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is just a concept. It doesn't compile.