Slide 1

Slide 1 text

Advanced Model-View-Intent The Missing Guide

Slide 2

Slide 2 text

Kostiantyn Tarasenko Hannes Dorfmann

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

class PersonsPresenter : Presenter { fun loadPersons(){ view?.showLoading(true) backend.loadPersons({ persons : List → view?.showLoading(false) view?.showPersons(persons) }, { error: Throwable → view?.showLoading(false) view?.showError(error) }) } }

Slide 5

Slide 5 text

class PersonsPresenter : Presenter { fun loadPersons(){ view?.showLoading(true) backend.loadPersons({ persons : List → view?.showLoading(false) view?.showPersons(persons) }, { error: Throwable → view?.showLoading(false) view?.showError(error) }) } }

Slide 6

Slide 6 text

class PersonsViewModel : ViewModel { val loading : LiveData val persons : LiveData> val error : LiveData fun loadPersons(){ loading.setValue( true ) backend.loadPersons({ p : List → loading.setValue( false ) persons.setValue( p ) }, { e : Throwable → loading.setValue( false ) error.setValue( e ) }) }

Slide 7

Slide 7 text

class PersonsViewModel : ViewModel { val loading : LiveData val persons : LiveData> val error : LiveData fun loadPersons(){ loading.setValue( true ) backend.loadPersons({ p : List → loading.setValue( false ) persons.setValue( p ) }, { e : Throwable → loading.setValue( false ) error.setValue( e ) }) }

Slide 8

Slide 8 text

public TrainingSpotsPresenter(TrainingSpotsMvp.View view, TrainingSpotsMvp.Model model, NetworkManager networkManager, FreeleticsTracking tracking, ScreenTrackingDelegate screenTrackingDelegate, EventBuildConfigInfo eventBuildConfigInfo) { this.model = model; this.view = view; this.networkManager = networkManager; this.tracking = tracking; this.screenTrackingDelegate = screenTrackingDelegate; this.eventBuildConfigInfo = eventBuildConfigInfo; subscriptions = new CompositeDisposable(); } @Override public void setTrackingScreenName() { screenTrackingDelegate.setScreenName(tracking, TrainingSpotsEvents.TRAINING_SPOT_LIST_PAGE_ID); } @Override public void loadTrainingSpots() { if (!networkManager.isOnline()) { view.showNoInternetConnection(); return; } view.showProgress(true); if (model.hasNoGpsPermissions()) { loadDefaultTrainingSpots(); } else { subscriptions.add(model.checkForHighAccuracy() .subscribe(status -> loadDefaultTrainingSpots(), throwable -> loadDefaultTrainingSpots(), () -> subscriptions.add( model.getNextTrainingSpots() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(trainingSpots -> { view.showProgress(false); view.showLocalTrainingSpots(trainingSpots, model.getNearbyTrainingSpotThreshold()); view.showShareNearbyTrainingSpotBanner( model.shouldShowBanner(trainingSpots)); tracking.trackEvent( TrainingSpotsEvents .pageImpressionTrainingSpotsList( eventBuildConfigInfo, true, trainingSpots));

Slide 9

Slide 9 text

model.shouldShowBanner(trainingSpots)); tracking.trackEvent( TrainingSpotsEvents .pageImpressionTrainingSpotsList( eventBuildConfigInfo, true, trainingSpots)); view.enablePaging(true); }, throwable -> { view.showProgress(false); if (throwable instanceof TimeoutException) { view.showTimeoutMessage(); } else { view.showConnectionError(); } })))); } } private void loadDefaultTrainingSpots() { subscriptions.add(model.getDefaultTrainingSpots() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(trainingSpots -> { view.showProgress(false); view.showDefaultTrainingSpots(trainingSpots); tracking.trackEvent(TrainingSpotsEvents.pageImpressionTrainingSpotsList( eventBuildConfigInfo, false, trainingSpots)); view.enablePaging(false); }, throwable -> { view.showProgress(false); view.showConnectionError(); })); } @Override public void loadMoreTrainingSpots() { if (!networkManager.isOnline()) { view.showNoInternetConnectionMessage(); view.enablePaging(false); return; } view.showLoadingMoreTrainingSpotsProgress(true); Disposable disposable = model.getNextTrainingSpots() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(trainingSpots -> { view.showLoadingMoreTrainingSpotsProgress(false);

Slide 10

Slide 10 text

.subscribe(trainingSpots -> { view.showLoadingMoreTrainingSpotsProgress(false); view.showMoreLocalTrainingSpots(trainingSpots, model.getNearbyTrainingSpotThreshold()); view.showShareNearbyTrainingSpotBanner(model.shouldShowBanner(trainingSpots)); }, throwable -> { view.showLoadingMoreTrainingSpotsProgress(false); view.showConnectionErrorMessage(); view.enablePaging(false); }); subscriptions.add(disposable); } @Override public void handleTrainingSpotSelection(TrainingSpot trainingSpot) { tracking.trackEvent(TrainingSpotsEvents.trainingSpotDetails(eventBuildConfigInfo, trainingSpot.id())); view.showTrainingSpotDetails(model.getLastKnownUserLocation(), trainingSpot); } @Override public void handleShareNearbyTrainingSpotAction() { view.openShareNearbySpotForm(model.getFormUrl()); } @Override public void handleFooterLocationAction() { if (model.hasNoGpsPermissions()) { view.showGpsPermissionDialog(GPS_PERMISSIONS_REQUEST_CODE); } else { checkForHighAccuracy(); } } @Override public void handleDisclaimerAction() { view.showDisclaimerPopUp(); } @Override public void handleChangeLocationSettingsResult(boolean success) { if (success) { if (model.hasNoGpsPermissions()) { view.showGpsPermissionDialog(GPS_PERMISSIONS_REQUEST_CODE); } else { loadTrainingSpots(); } } else { view.showEnableHighAccuracyModeErrorDialog(); }

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

intent

Slide 16

Slide 16 text

intent state render (state)

Slide 17

Slide 17 text

intent state render (state)

Slide 18

Slide 18 text

sealed class State { object Loading : State() data class Content(val persons : List) : State() data class Error(val error : Throwable) : State() }

Slide 19

Slide 19 text

https://youtu.be/YGmxbwI3a-4

Slide 20

Slide 20 text

intent state render (state)

Slide 21

Slide 21 text

State Management

Slide 22

Slide 22 text

View ViewModel / Presenter State Machine

Slide 23

Slide 23 text

View ViewModel / Presenter State Machine Intent

Slide 24

Slide 24 text

View ViewModel / Presenter State Machine Intent Input

Slide 25

Slide 25 text

View ViewModel / Presenter State Machine Intent Input State

Slide 26

Slide 26 text

View ViewModel / Presenter State Machine Intent Input State View State

Slide 27

Slide 27 text

Wednesday June 27 2:50 PM - Room Cupcake

Slide 28

Slide 28 text

Simple State Machines val httpRequest : Observable> = ... val state : Observable = ???

Slide 29

Slide 29 text

sealed class State { object Loading : State() data class Content(val persons : List) : State() data class Error(val error : Throwable) : State() }

Slide 30

Slide 30 text

Simple State Machines val httpRequest : Observable> = ... val state : Observable = httpRequest .map { persons → State.Content(persons) } .onErrorReturn { State.Error(it) } .startWith(State.Loading)

Slide 31

Slide 31 text

Simple State Machines val httpRequest : Observable> = ... val state : Observable = httpRequest .map { persons → State.Content(persons) } .onErrorReturn { State.Error(it) } .startWith(State.Loading)

Slide 32

Slide 32 text

Simple State Machines val httpRequest : Observable> = ... val state : Observable = httpRequest .map { persons → State.Content(persons) } .onErrorReturn { State.Error(it) } .startWith(State.Loading)

Slide 33

Slide 33 text

Simple State Machines val sm1: Observable = … val sm2: Observable = ... val combined: Observable = Observable.zip(sm1, sm2){ s1,s2 → ... })

Slide 34

Slide 34 text

Simple State Machines val sm1: Observable = … val sm2: Observable = ... val combined: Observable = Observable.zip(sm1, sm2){ s1,s2 → if (s1 is State.Error) s1 ... })

Slide 35

Slide 35 text

Simple State Machines val sm1: Observable = … val sm2: Observable = ... val combined: Observable = Observable.zip(sm1, sm2){ s1,s2 → if (s1 is State.Error) s1 if (s2 is State.Error) s2 ... })

Slide 36

Slide 36 text

Simple State Machines val sm1: Observable = … val sm2: Observable = ... val combined: Observable = Observable.zip(sm1, sm2){ s1,s2 → if (s1 is State.Error) s1 if (s2 is State.Error) s2 if (s1 == State.Loading || s2 == State.Loading) State.Loading ... })

Slide 37

Slide 37 text

Simple State Machines val http1: Observable> = … val http2: Observable> = ... val combined: Observable = Observable.zip(http1, http2 ){ p1,p2 → p1 + p2 }) .map { persons → State.Content(persons) } .onErrorReturn { State.Error(it) } .startWith(State.Loading)

Slide 38

Slide 38 text

Advanced State Machines

Slide 39

Slide 39 text

class CalculatorStateMachine { }

Slide 40

Slide 40 text

class CalculatorStateMachine { sealed class Input { data class Add(val value: Int) : Input() data class Sub(val value: Int) : Input() data class Mul(val value: Int) : Input() data class Div(val value: Int) : Input() } }

Slide 41

Slide 41 text

class CalculatorStateMachine { sealed class Input { ... } sealed class State { data class Result(val value: Int) : State() data class Error(val error: Throwable) : State() } }

Slide 42

Slide 42 text

class CalculatorStateMachine { sealed class Input { ... } sealed class State { ... } private val inputRelay = PublishRelay.create() }

Slide 43

Slide 43 text

class CalculatorStateMachine { sealed class Input { ... } sealed class State { ... } private val inputRelay = PublishRelay.create() val input : Consumer = inputRelay }

Slide 44

Slide 44 text

class CalculatorStateMachine { sealed class Input { ... } sealed class State { ... } private val inputRelay = PublishRelay.create() val input : Consumer = inputRelay val state: Observable = inputRelay.map { ... } }

Slide 45

Slide 45 text

class CalculatorStateMachine { sealed class Input { ... } sealed class State { ... } private val inputRelay = PublishRelay.create() val input : Consumer = inputRelay val state: Observable = inputRelay.map { ... } }

Slide 46

Slide 46 text

State Reducer .scan(State.Loading) { currentState , input → // compute new state … }

Slide 47

Slide 47 text

Fancy Redux Based State Machines - Store → Observable for State - Actions as input - Reducer: (State , Action ) → State - Isolate Side Effects

Slide 48

Slide 48 text

Fancy Redux Based State Machines

Slide 49

Slide 49 text

Tuesday June 26 11:05 AM - Room Lollipop

Slide 50

Slide 50 text

Tuesday June 26 11:05 AM - Room Oreo

Slide 51

Slide 51 text

Intent? Action?

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

View ViewModel / Presenter State Machine Intent Intent State View State

Slide 54

Slide 54 text

View ViewModel / Presenter State Machine Intent Intent State View State .scan( )

Slide 55

Slide 55 text

View ViewModel / Presenter Redux State Machine Intent Action State View State Action triggered by side effect

Slide 56

Slide 56 text

No content

Slide 57

Slide 57 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State

Slide 58

Slide 58 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State Next page

Slide 59

Slide 59 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State Next page Next page

Slide 60

Slide 60 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State Next page Next page

Slide 61

Slide 61 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State Next page

Slide 62

Slide 62 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State LoadingPage

Slide 63

Slide 63 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State LoadingPage

Slide 64

Slide 64 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State LoadingPage

Slide 65

Slide 65 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State

Slide 66

Slide 66 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State

Slide 67

Slide 67 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State ResultNextPage

Slide 68

Slide 68 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State ResultNextPage

Slide 69

Slide 69 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State ResultNextPage

Slide 70

Slide 70 text

View Redux State Machine reducer(state, action) : State nextPage(nextPageAction) : Action State

Slide 71

Slide 71 text

View Redux State Machine reducer(state, action) : State Side Effect 1 State Side Effect 2 Side Effect n ...

Slide 72

Slide 72 text

val sideEffects = listOf< SideEffect >( ... nextPageSideEffect, pullToRefreshSideEffect, ... ) intents .reduxStore(initialState, sideEffects, reducer) .subscribe { state → view.render(state) } https://github.com/freeletics/RxRedux

Slide 73

Slide 73 text

Testing

Slide 74

Slide 74 text

Testing is easy - assert(expectedState, actualState) - Just trigger intent, wait for state change - No need for idling resource needed - Prefer integration testing over unit testing

Slide 75

Slide 75 text

class MyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { ... val button = findViewById(R.id.button) ... } fun render(state: State) { ... } }

Slide 76

Slide 76 text

class MyActivity : Activity() { @Inject lateinit var binding : ViewBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // inject binding ... } fun render(state: State) { binding.render() } }

Slide 77

Slide 77 text

class ViewBinding(val rootView : View) { val button = rootView.findViewById(R.id.button) fun render(state: State) { ... } }

Slide 78

Slide 78 text

class TestingViewBinding(rootView : View) : ViewBinding { val renderdStates : Observable = replay private val replay = ReplayRelay.create() override fun render(state: State) { super.render(state) replay.onNext(state) Screenshot.snap(rootView).record() } }

Slide 79

Slide 79 text

class TestingViewBinding(rootView : View) : ViewBinding { val renderdStates : Observable = replay private val replay = ReplayRelay.create() override fun render(state: State) { super.render(state) replay.onNext(state) Screenshot.snap(rootView).record() } }

Slide 80

Slide 80 text

class TestingViewBinding(rootView : View) : ViewBinding { val renderdStates : Observable = replay private val replay = ReplayRelay.create() override fun render(state: State) { super.render(state) replay.onNext(state) Screenshot.snap(rootView).record() } }

Slide 81

Slide 81 text

class TestingViewBinding(rootView : View) : ViewBinding { val renderdStates : Observable = replay private val replay = ReplayRelay.create() override fun render(state: State) { super.render(state) replay.onNext(state) Screenshot.snap(rootView).record() } }

Slide 82

Slide 82 text

class TestingViewBinding(rootView : View) : ViewBinding { val renderdStates : Observable = replay private val replay = ReplayRelay.create() override fun render(state: State) { super.render(state) replay.onNext(state) Screenshot.snap(rootView).record() } } https://facebook.github.io/screenshot-tests-for-android/

Slide 83

Slide 83 text

Tracking

Slide 84

Slide 84 text

Multicasting

Slide 85

Slide 85 text

RxJava By Example - Vol 3. the Multicast Edition

Slide 86

Slide 86 text

intents .share() .subscribe { intent -> when (intent) { NextButtonClick -> tracker.trackNextButtonClick() ... } }

Slide 87

Slide 87 text

stateMachine .share() .subscribe { state -> when (state) { is StateA -> tracker.trackStateA() ... } }

Slide 88

Slide 88 text

No content

Slide 89

Slide 89 text

Navigation

Slide 90

Slide 90 text

sealed class State { data class UserData( val login: String, val password: String ) : State() data class SingingIn( val login: String, val password: String ) : State() data class Error( val login: String, val password: String, val errorMessage: String, ) : State() object SignedIn : State() }

Slide 91

Slide 91 text

sealed class State { data class UserData( val login: String, val password: String ) : State() data class SingingIn( val login: String, val password: String ) : State() data class Error( val login: String, val password: String, val errorMessage: String, ) : State() object SignedIn : State( } fun render(state: State) { when (state) { State.SignedIn -> { startActivity(nextActivityIntent()) finish() } ... } }

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

Navigator stateMachine .share() .subscribe { state -> when (state) { ... -> navigator.navigateTo(Destination.OptionalQuestions) } }

Slide 94

Slide 94 text

Navigator stateMachine .share() .subscribe { state -> when (state) { ... -> navigator.navigateTo(Destination.OptionalQuestions) } } class WizardNavigator( private val activity: Activity, private val abTestProvider: AbTestProvider ) : Navigator { override fun navigateTo(dest: Destination) { when (dest) { Destination.Form -> showFormFragment() Destination.OptionalQuestions -> showOptionalQuestionsFragment() Destination.VariantSelector -> showVariantSelectorFragment() Destination.FromSaved -> activity.startActivity(abTestProvider.nextScreen()) } } }

Slide 95

Slide 95 text

Navigator implementation Deep inside, the Navigator implementation could be as simple as override fun navigateTo(dest: Destination) { when (dest) { Destination.Next -> showNextActivity() ... } } fun showNextActivity() { activity.startActivity( if (FeatureFlag.A) { activityOneIntent() } else { activityTwoIntent() } ) }

Slide 96

Slide 96 text

Navigator implementation Or be little bit modern override fun navigateTo(dest: Destination) { when (dest) { Destination.Next -> showNextActivity() ... } } fun showNextActivity() { view.findNavController().navigate(R.id.wizard_next_activity) }

Slide 97

Slide 97 text

Animation

Slide 98

Slide 98 text

Animation private sealed class InternalAnimationState { object InitialState : InternalAnimationState() object ProgressTransition : InternalAnimationState() data class Progress( val textResId: Int, val currentProgressPercent: Int, val totalProgressDuration: Long ) : InternalAnimationState() object GenerationFinished : InternalAnimationState() }

Slide 99

Slide 99 text

Animation object InitialState :InternalAnimationState()

Slide 100

Slide 100 text

Animation object ProgressTransition :InternalAnimationState()

Slide 101

Slide 101 text

Animation data class Progress( val textResId: Int, val currentProgressPercent: Int, val totalProgressDuration: Long ) :InternalAnimationState()

Slide 102

Slide 102 text

Animation object GenerationFinished :InternalAnimationState()

Slide 103

Slide 103 text

Animation private fun createAnimationStateObservable(): Observable = Observable.merge( intents.filter { it == GenerationClicked } .map { ProgressTransition }, intents.filter { it == GenerationStarted } .flatMap { Observable.intervalRange( 0, steps, 0, duration / steps, TimeUnit.MILLISECONDS ).map { it.toInt() } .map { if (step == size) { GenerationFinished } else { Progress(...) } } })

Slide 104

Slide 104 text

Animation private fun createAnimationState(): Observable = rxObservable { intents.consumeEach { intent -> when (intent) { GenerationClicked -> send(ProgressTransition) GenerationStarted -> { repeat(size) { step -> delay(duration / size) send(if (step == texts.size) { GenerationFinished } else { Progress(...) }) } } } } }

Slide 105

Slide 105 text

Animation private fun createAnimationState(): Observable = rxObservable { intentStream.consumeEach { intent -> when (intent) { GenerationClicked -> send(ProgressTransition) GenerationStarted -> { repeat(size) { step -> delay(duration / size) send(if (step == texts.size) { GenerationFinished } else { Progress(...) }) } } } } }

Slide 106

Slide 106 text

Restoring state

Slide 107

Slide 107 text

No content

Slide 108

Slide 108 text

enum class Variant { Variant1, Variant2 } data class Step1State( val selected: Variant )

Slide 109

Slide 109 text

enum class Variant { Variant1, Variant2 } data class Step1State( val selected: Variant ) data class Step2State( val option1Checked: Boolean, val option2Checked: Boolean )

Slide 110

Slide 110 text

enum class Variant { Variant1, Variant2 } data class Step1State( val selected: Variant ) data class Step2State( val option1Checked: Boolean, val option2Checked: Boolean ) data class Step3State( val name : String, val description : String )

Slide 111

Slide 111 text

data class WizardState( val currentScreenIndex: Int, val step1State: Step1State, val step2State: Step2State, val step3State: Step3State )

Slide 112

Slide 112 text

Tips and tricks

Slide 113

Slide 113 text

How to handle onActivityResult?

Slide 114

Slide 114 text

No content

Slide 115

Slide 115 text

onRequestPermissionResult()?

Slide 116

Slide 116 text

No content

Slide 117

Slide 117 text

What about Lifecycle callback?

Slide 118

Slide 118 text

No content

Slide 119

Slide 119 text

Rendering state too fast?

Slide 120

Slide 120 text

No content

Slide 121

Slide 121 text

No content

Slide 122

Slide 122 text

No content

Slide 123

Slide 123 text

How to refactor existing code to MVI?

Slide 124

Slide 124 text

Refactoring 1. Define States 2. MVP: replace all view.showX() → view.render(state) MVVM: replace all LiveData → LiveData 3. Define a state machine with a clear API Inputs and Outputs 4. Define Intents that trigger inputs on state machine 5. Trigger Intents from view layer

Slide 125

Slide 125 text

Questions?

Slide 126

Slide 126 text

Links - The State of Representing State by Christina Lee - RxJava By Example - Vol 3. the Multicast Edition by Kaushik Gopal - Screenshot testing: https://facebook.github.io/screenshot-tests-for-android/ - https://github.com/freeletics/RxRedux