Slide 1

Slide 1 text

Unidirectional Data Flow on Android David González @dggonzalez [email protected] Droidcon Italy 2019

Slide 2

Slide 2 text

Credit when credit is due… Fernando Cejas Cesar Valiente Fabio Collini

Slide 3

Slide 3 text

View ViewModel Store Reducer Action State send interpret dispatch notify

Slide 4

Slide 4 text

View ViewModel Action

Slide 5

Slide 5 text

sealed class OrdersViewAction { object NavigateToChatScreen : OrdersViewAction() data class SelectAddress(val orderId: String) : OrdersViewAction() data class CancelOrder(val orderId: String) : OrdersViewAction() data class TrackShipment(val url: String) : OrdersViewAction() }

Slide 6

Slide 6 text

open class MainViewModel : ViewModel() { val store: Store = Store() fun observe(owner: LifecycleOwner, stateObserver: (ViewState) -> Unit) = store.stateLiveData.observe(owner, Observer { observer(it!!) }) fun interpret(action: ViewAction) override fun onCleared() { store.cancel() } }

Slide 7

Slide 7 text

open class MainViewModel : ViewModel() { val store: Store = Store() fun observe(owner: LifecycleOwner,stateObserver: (ViewState) -> Unit) = store.stateLiveData.observe(owner, Observer { observer(it!!) }) fun interpret(action: ViewAction) override fun onCleared() { store.cancel() } }

Slide 8

Slide 8 text

open class MainViewModel : ViewModel() { val store: Store = Store() fun observe(owner: LifecycleOwner, stateObserver: (ViewState) -> Unit) = store.stateLiveData.observe(owner, Observer { observer(it!!) }) fun interpret(action: ViewAction) override fun onCleared() { store.cancel() } }

Slide 9

Slide 9 text

val store: Store = Store() fun observe(owner: LifecycleOwner, stateObserver: (ViewState) -> Unit) = store.stateLiveData.observe(owner, Observer { observer(it!!) }) fun interpret(action: ViewAction) override fun onCleared() { store.cancel() } }

Slide 10

Slide 10 text

store.stateLiveData.observe(owner, Observer { observer(it!!) }) fun interpret(action: ViewAction) override fun onCleared() { store.cancel() } }

Slide 11

Slide 11 text

ViewModel Store Reducer Action State

Slide 12

Slide 12 text

class Store(initialState: ViewState = ViewState.Idle){ val stateLiveData = MutableLiveData() .apply { value = initialState } @MainThread fun dispatchState(state: ViewState) { stateLiveData.value = state } }

Slide 13

Slide 13 text

class Store(initialState: ViewState = ViewState.Idle){ val stateLiveData = MutableLiveData() .apply { value = initialState } @MainThread fun dispatchState(state: ViewState) { stateLiveData.value = state } }

Slide 14

Slide 14 text

class Store(initialState: ViewState = ViewState.Idle){ val stateLiveData = MutableLiveData() .apply { value = initialState } @MainThread fun dispatchState(state: ViewState) { stateLiveData.value = state } }

Slide 15

Slide 15 text

class Store(initialState: ViewState = ViewState.Idle) : CoroutineScope { private val job = Job() fun cancel() = job.cancel() override val coroutineContext: CoroutineContext = job + Dispatchers.IO private fun state() = stateLiveData.value!! fun dispatchState(f: suspend (ViewState) -> State) { launch { val action = f(state()) withContext(Dispatchers.Main) { dispatchState(action(state())) }

Slide 16

Slide 16 text

class Store(initialState: ViewState = ViewState.Idle) : CoroutineScope { private val job = Job() fun cancel() = job.cancel() override val coroutineContext: CoroutineContext = job + Dispatchers.IO private fun state() = stateLiveData.value!! fun dispatchState(f: suspend (ViewState) -> State) { launch { val action = f(state()) withContext(Dispatchers.Main) { dispatchState(action(state())) }

Slide 17

Slide 17 text

class Store(initialState: ViewState = ViewState.Idle) : CoroutineScope { private val job = Job() fun cancel() = job.cancel() override val coroutineContext: CoroutineContext = job + Dispatchers.IO private fun state() = stateLiveData.value!! fun dispatchState(f: suspend (ViewState) -> State) { launch { val action = f(state()) withContext(Dispatchers.Main) { dispatchState(action(state())) }

Slide 18

Slide 18 text

class Store(initialState: ViewState = ViewState.Idle) : CoroutineScope { private val job = Job() fun cancel() = job.cancel() override val coroutineContext: CoroutineContext = job + Dispatchers.IO private fun state() = stateLiveData.value!! fun dispatchState(f: suspend (ViewState) -> State) { launch { val reducer = f(state()) withContext(Dispatchers.Main) { dispatchState(reducer(state())) } }

Slide 19

Slide 19 text

private val job = Job() fun cancel() = job.cancel() override val coroutineContext: CoroutineContext = job + Dispatchers.IO private fun state() = stateLiveData.value!! fun dispatchState(f: suspend (ViewState) -> State) { launch { val reducer = f(state()) withContext(Dispatchers.Main) { dispatchState(reducer(state())) } } } }

Slide 20

Slide 20 text

fun cancel() = job.cancel() override val coroutineContext: CoroutineContext = job + Dispatchers.IO private fun state() = stateLiveData.value!! fun dispatchState(f: suspend (ViewState) -> State) { launch { val reducer = f(state()) withContext(Dispatchers.Main) { dispatchState(reducer(state())) } } } }

Slide 21

Slide 21 text

private fun state() = stateLiveData.value!! fun dispatchState(f: suspend (ViewState) -> State) { launch { val reducer = f(state()) withContext(Dispatchers.Main) { dispatchState(reducer(state())) } } } }

Slide 22

Slide 22 text

private fun state() = stateLiveData.value!! fun dispatchState(f: suspend (ViewState) -> State) { launch { val reducer = f(state()) withContext(Dispatchers.Main) { dispatchState(reducer(state())) } } } }

Slide 23

Slide 23 text

class PitchReducer @Inject constructor(val testimonialsRepo: TestimonialsRepository, val pricingRepo: PricingRepository){ operator fun invoke() = loadPitch() private fun loadPitch(): State { val testimonials = testimonialsRepo.all() val pricing = pricingRepo.current() return State { Pitch(testimonials, pricing) } } }

Slide 24

Slide 24 text

class PitchReducer @Inject constructor(val testimonialsRepo: TestimonialsRepository, val pricingRepo: PricingRepository){ operator fun invoke() = loadPitch() private fun loadPitch(): State { val testimonials = testimonialsRepo.all() val pricing = pricingRepo.current() return State { Pitch(testimonials, pricing) } } }

Slide 25

Slide 25 text

class PitchReducer @Inject constructor(val testimonialsRepo: TestimonialsRepository, val pricingRepo: PricingRepository){ operator fun invoke() = loadPitch() private fun loadPitch(): State { val testimonials = testimonialsRepo.all() val pricing = pricingRepo.current() return State { Pitch(testimonials, pricing) } } }

Slide 26

Slide 26 text

class PitchReducer @Inject constructor(val testimonialsRepo: TestimonialsRepository, val pricingRepo: PricingRepository){ operator fun invoke() = loadPitch() private fun loadPitch(): State { val testimonials = testimonialsRepo.all() val pricing = pricingRepo.current() return State { Pitch(testimonials, pricing) } } }

Slide 27

Slide 27 text

private fun initViewModel() { viewModel=ViewModelProviders.of(this,vmf)[…] viewModel.observe(this, ::renderViewState) } override fun renderViewState(viewState: ViewState) { when (viewState) { is Pitch -> renderPitch(viewState) } } PitchActivity

Slide 28

Slide 28 text

class PitchViewModel @Inject constructor(private val reducer: PitchReducer): MainViewModel(){ fun interpret(action: ViewAction) { return when (action) { is LoadPitch -> store.dispatchState(reducer()) else -> throw IncompatibleActionException() } } PitchViewModel

Slide 29

Slide 29 text

class PitchViewModel @Inject constructor(private val reducer: PitchReducer): MainViewModel(){ fun interpret(action: ViewAction) { return when (action) { is LoadPitch -> store.dispatchState(reducer()) else -> throw IncompatibleActionException() } } PitchViewModel

Slide 30

Slide 30 text

class PitchViewModel @Inject constructor(private val reducer: PitchReducer): MainViewModel(){ fun interpret(action: ViewAction) { return when (action) { is LoadPitch -> store.dispatchState(reducer()) else -> throw IncompatibleActionException() } } PitchViewModel

Slide 31

Slide 31 text

class PitchViewModel @Inject constructor(private val reducer: PitchReducer): MainViewModel(){ fun interpret(action: ViewAction) { return when (action) { is LoadPitch -> store.dispatchState(reducer()) else -> throw IncompatibleActionException() } } PitchViewModel

Slide 32

Slide 32 text

class PitchViewModel @Inject constructor(private val reducer: PitchReducer): MainViewModel(){ fun interpret(action: ViewAction) { return when (action) { is LoadPitch -> store.dispatchState(reducer()) else -> throw IncompatibleActionException() } } PitchViewModel

Slide 33

Slide 33 text

Problems going forward How do you deal with a more complicated ViewState? How do you deal with an error? How do you deal with multiple errors that must be displayed in screen?

Slide 34

Slide 34 text

data class Address(val order: Order = Order.empty(), val wrongCity: Boolean, val wrongCountry: Boolean, val wrongAddress: Boolean, val isLoading: Boolean, val isCompleted: Boolean, val exception: Exception) : ViewState() } ViewState

Slide 35

Slide 35 text

private fun render(viewState: Address) { if (viewState.isCompleted){ finish() else { progress.isVisible = viewState.isLoading viewState.exception?.let{ renderException(it) } cityError.isVisible = viewState.wrongCity countryError.isVisible = viewState.wrongCountry addressError.isVisible = viewState.wrongAddress renderOrder(order) } } Activity

Slide 36

Slide 36 text

private fun render(viewState: Address) { if (viewState.isCompleted){ renderCompleted() else { progress.isVisible = viewState.isLoading viewState.exception?.let{ renderException(it) } cityError.isVisible = viewState.wrongCity countryError.isVisible = viewState.wrongCountry addressError.isVisible = viewState.wrongAddress renderOrder(order) } } Activity

Slide 37

Slide 37 text

private fun render(viewState: Address) { if (viewState.isCompleted){ renderCompleted() else { progress.isVisible = viewState.isLoading viewState.exception?.let{ renderException(it) } cityError.isVisible = viewState.wrongCity countryError.isVisible = viewState.wrongCountry addressError.isVisible = viewState.wrongAddress renderOrder(order) } }

Slide 38

Slide 38 text

private fun render(viewState: Address) { if (viewState.isCompleted){ renderCompleted() else { progress.isVisible = viewState.isLoading viewState.exception?.let{ renderException(it) } cityError.isVisible = viewState.wrongCity countryError.isVisible = viewState.wrongCountry addressError.isVisible = viewState.wrongAddress renderOrder(order) } }

Slide 39

Slide 39 text

renderCompleted() else { progress.isVisible = viewState.isLoading viewState.exception?.let{ renderException(it) } cityError.isVisible = viewState.wrongCity countryError.isVisible = viewState.wrongCountry addressError.isVisible = viewState.wrongAddress renderOrder(order) } }

Slide 40

Slide 40 text

progress.isVisible = viewState.isLoading viewState.exception?.let{ renderException(it) } cityError.isVisible = viewState.wrongCity countryError.isVisible = viewState.wrongCountry addressError.isVisible = viewState.wrongAddress renderOrder(order) } }

Slide 41

Slide 41 text

sealed class ChangeAddressViewAction { object TalkToUs : ChangeAddressViewAction() data class LoadOrder(val orderId: String): ChangeAddressViewAction() data class ChangeAddress( val orderId: String, val shippingAddress: ShippingAddress): ChangeAddressViewAction() } Action

Slide 42

Slide 42 text

fun interpret(action: ChangeAddressViewAction) { when (action) { is LoadOrder -> loadOrder(action.orderId) is ChangeAddress -> changeAddress(action) is TalkToUs -> navigator.toChat() } } private fun changeAddress(orderId: String, address: ShippingAddress) { store.dispatchState { State { Loading } } store.dispatchState (changeOrderAddress(orderId, shippingAddress)) } ViewModel

Slide 43

Slide 43 text

when (action) { is LoadOrder -> loadOrder(action.orderId) is ChangeAddress -> changeAddress(action) is TalkToUs -> navigator.toChat() } } private fun changeAddress(orderId: String, address: ShippingAddress) { store.dispatchState { State { Loading } } store.dispatchState { changeOrderAddress(orderId, shippingAddress)} }

Slide 44

Slide 44 text

Moar problems… Navigation Event vs View State ViewModel is calling store twice, once per state

Slide 45

Slide 45 text

sealed class Either { // Represents the left side of Either class // which by convention is a "Failure" data class Left(val a: L) : Either() //Represents the right side of Either class //which by convention is a "Success" data class Right(val b: R) : Either() } https://arrow-kt.io/docs/arrow/core/either/

Slide 46

Slide 46 text

sealed class Failure { // App wide failures data class ServerError(val error: String) : Failure() object NetworkConnection : Failure() data class GenericError(val exception: Exception) : Failure() // Extend this class for feature specific failures abstract class FeatureFailure : Failure() }

Slide 47

Slide 47 text

sealed class Success { // Extend this classes for feature specific success abstract class ViewState : Success() abstract class ViewEvent : Success() // App wide success view states object Idle : ViewState() object Loading : ViewState() }

Slide 48

Slide 48 text

class Store(initialState: ViewState) : CoroutineScope { val stateLiveData = MutableLiveData>() .apply { value = initialState } fun dispatchState(f: suspend (Either) -> State>) { launch { val reducer = f(state()) withContext(Dispatchers.Main) { dispatchState(reducer(state())) }

Slide 49

Slide 49 text

class Store(initialState: ViewState) : CoroutineScope { val stateLiveData = MutableLiveData>() .apply { value = initialState } fun dispatchState(f: suspend (Either) -> State>) { launch { val reducer = f(state()) withContext(Dispatchers.Main) { dispatchState(reducer(state())) }

Slide 50

Slide 50 text

class Store(initialState: ViewState) : CoroutineScope { val stateLiveData = MutableLiveData>() .apply { value = initialState } fun dispatchState(f: suspend (Either) -> State>) { launch { val reducer = f(state()) withContext(Dispatchers.Main) { dispatchState(reducer(state())) }

Slide 51

Slide 51 text

val stateLiveData = MutableLiveData>() .apply { value = initialState } fun dispatchState(f: suspend (Either) -> State>) { launch { val reducer = f(state()) withContext(Dispatchers.Main) { dispatchState(reducer(state())) }

Slide 52

Slide 52 text

open class MainViewModel : ViewModel() { private val successLiveData = LiveData() private val failureLiveData = LiveData() fun observe(owner: LifecycleOwner, successObserver: (Success) -> Unit, failureObserver: (Failure) -> Unit) { successLiveData.observe(owner, Observer { successObserver(it!!) }) failureLiveData.observe(owner, Observer { failureObserver(it) }) store.observeState(owner) { when (it) {

Slide 53

Slide 53 text

open class MainViewModel : ViewModel() { private val successLiveData = LiveData() private val failureLiveData = LiveData() fun observe(owner: LifecycleOwner, successObserver: (Success) -> Unit, failureObserver: (Failure) -> Unit) { successLiveData.observe(owner, Observer { successObserver(it!!) }) failureLiveData.observe(owner, Observer { failureObserver(it) }) store.observeState(owner) { when (it) {

Slide 54

Slide 54 text

open class MainViewModel : ViewModel() { private val successLiveData = LiveData() private val failureLiveData = LiveData() fun observe(owner: LifecycleOwner, successObserver: (Success) -> Unit, failureObserver: (Failure) -> Unit) { successLiveData.observe(owner, Observer { successObserver(it!!) }) failureLiveData.observe(owner, Observer { failureObserver(it) }) store.observeState(owner) { when (it) { is Either.Left -> failureLiveData.value = it.a is Either.Right -> successLiveData.value = it.b

Slide 55

Slide 55 text

private val failureLiveData = LiveData() fun observe(owner: LifecycleOwner, successObserver: (Success) -> Unit, failureObserver: (Failure) -> Unit) { successLiveData.observe(owner, Observer { successObserver(it!!) }) failureLiveData.observe(owner, Observer { failureObserver(it) }) store.observeState(owner) { when (it) { is Either.Left -> failureLiveData.value = it.a is Either.Right -> successLiveData.value = it.b } }

Slide 56

Slide 56 text

failureObserver: (Failure) -> Unit) { successLiveData.observe(owner, Observer { successObserver(it!!) }) failureLiveData.observe(owner, Observer { failureObserver(it) }) store.observeState(owner) { when (it) { is Either.Left -> failureLiveData.value = it.a is Either.Right -> successLiveData.value = it.b } }

Slide 57

Slide 57 text

data class Address(val order: Order = Order.empty(), val wrongCity: Boolean, val wrongCountry: Boolean, val wrongAddress: Boolean, val isLoading: Boolean, val isCompleted: Boolean, val exception: Exception) : ViewState() }

Slide 58

Slide 58 text

data class Address(val order: Order = Order.empty()) : Success.ViewState() object TalkToUs : Success.ViewEvent() object AddressChanged : Success.ViewEvent() data class InvalidAddress(val wrongCity: Boolean, val wrongCountry: Boolean, val wrongAddress: Boolean) : FeatureFailure()

Slide 59

Slide 59 text

viewModel = ViewModelProviders.of(this, viewModelFactory)[MyViewModel::class.java] viewModel.observe(this, ::renderSuccess, ::renderFailure) protected fun renderSuccess(success: Success) { when (success) { is Success.ViewEvent -> reactToEvent(success) is Success.ViewState -> renderViewState(success) } } override fun renderViewState(viewState: Success.ViewState) { when (viewState) { Activity

Slide 60

Slide 60 text

viewModel = ViewModelProviders.of(this, viewModelFactory)[MyViewModel::class.java] viewModel.observe(this, ::renderSuccess, ::renderFailure) protected fun renderSuccess(success: Success) { when (success) { is Success.ViewEvent -> reactToEvent(success) is Success.ViewState -> renderViewState(success) } } override fun renderViewState(viewState: Success.ViewState) { when (viewState) { is Orders -> renderOrders(viewState) } }

Slide 61

Slide 61 text

when (success) { is Success.ViewEvent -> reactToEvent(success) is Success.ViewState -> renderViewState(success) } } override fun renderViewState(viewState: Success.ViewState) { when (viewState) { is Orders -> renderOrders(viewState) } } override fun reactToEvent(event: Success.ViewEvent) { when (event) { is Success.TalkToUs -> navigator.toSupportChat() is SelectAddress -> navigator.toChangeAddress(this, event.orderId) is OrderCancelled -> displaySnackbar(event.failureMessage) is CancelOrder -> navigator.toCancelOrder(this, event.orderId)

Slide 62

Slide 62 text

override fun renderViewState(viewState: Success.ViewState) { when (viewState) { is Orders -> renderOrders(viewState) } } override fun reactToEvent(event: Success.ViewEvent) { when (event) { is Success.TalkToUs -> navigator.toSupportChat() is SelectAddress -> navigator.toChangeAddress(this, event.orderId) is OrderCancelled -> displaySnackbar(event.failureMessage) is CancelOrder -> navigator.toCancelOrder(this, event.orderId) is TrackShipment -> navigator.toTrackingShipment(event.url) } } override fun renderFailure(failure: Failure) { ordersList.gone()

Slide 63

Slide 63 text

is Success.TalkToUs -> navigator.toSupportChat() is SelectAddress -> navigator.toChangeAddress(this, event.orderId) is OrderCancelled -> displaySnackbar(event.failureMessage) is CancelOrder -> navigator.toCancelOrder(this, event.orderId) is TrackShipment -> navigator.toTrackingShipment(event.url) } } override fun renderFailure(failure: Failure) { ordersList.gone() loading.gone() empty.show() }

Slide 64

Slide 64 text

The final step…

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

public interface SendChannel { public suspend fun send(element: E) public fun offer(element: E) public fun close(cause: Throwable? = null): Boolean } public interface ReceiveChannel { public suspend fun receive(): E public fun close(cause: Throwable? = null): Boolean } Deferred vs Channel

Slide 67

Slide 67 text

fun main() = runBlocking { val channel = Channel() launch { for (i in 1..5) { channel.send(i) } launch { for (value in channel) { println("received: $value") } //console output received: 1 received: 2 received: 3 received: 4 received: 5 Channel

Slide 68

Slide 68 text

fun main() = runBlocking { val channel = Channel() launch { for (i in 1..5) { channel.send(i) } launch { for (value in channel) { println("received: $value") } //console output received: 1 received: 2 received: 3 received: 4 received: 5 Channel

Slide 69

Slide 69 text

fun main() = runBlocking { val channel = Channel() launch { for (i in 1..5) { channel.send(i) } launch { for (value in channel) { println("received: $value") } //console output received: 1 received: 2 received: 3 received: 4 received: 5 Channel

Slide 70

Slide 70 text

fun main() = runBlocking { val channel = Channel() launch { for (i in 1..5) { channel.send(i) } launch { for (value in channel) { println("received: $value") } //console output received: 1 received: 2 received: 3 received: 4 received: 5 Channel

Slide 71

Slide 71 text


 public fun CoroutineScope.produce( context: CoroutineContext = EmptyCoroutineContext, capacity: Int = 0, block: suspend ProducerScope.() -> Unit ): ReceiveChannel Producer

Slide 72

Slide 72 text

val publisher = produce(capacity = 2){ for (i in 1..5){ send(i) } launch { publisher.consumeEach { println("received: $it”) } } //console output received: 1 received: 2 received: 3 received: 4 received: 5 Producer

Slide 73

Slide 73 text

val publisher = produce(capacity = 2){ for (i in 1..5){ send(i) } launch { publisher.consumeEach { println("received: $it”) } } //console output received: 1 received: 2 received: 3 received: 4 received: 5 Producer

Slide 74

Slide 74 text

val publisher = produce(capacity = 2){ for (i in 1..5){ send(i) } launch { publisher.consumeEach { println("received: $it”) } } //console output received: 1 received: 2 received: 3 received: 4 received: 5 Producer

Slide 75

Slide 75 text

val publisher = produce(capacity = 2){ for (i in 1..5){ send(i) } launch { publisher.consumeEach { println("received: $it”) } } //console output received: 1 received: 2 received: 3 received: 4 received: 5 Producer

Slide 76

Slide 76 text

open class Reducer { suspend fun ProducerScope>.send(f: T.() -> T) = send(State(f)) fun produceStates(f: suspend ProducerScope>.() -> Unit) : ReceiveChannel> = GlobalScope.produce(block = f) }

Slide 77

Slide 77 text

open class Reducer { suspend fun ProducerScope>.send(f: T.() -> T) = send(State(f)) fun produceStates(f: suspend ProducerScope>.() -> Unit) : ReceiveChannel> = GlobalScope.produce(block = f) }

Slide 78

Slide 78 text

fun dispatchStates(channel: ReceiveChannel>>) { launch { channel.consumeEach { reducer -> withContext(Dispatchers.Main) { dispatchState(reducer(state())) } } } } fun loadOrders() { store.dispatchStates(getOrders()) } Store

Slide 79

Slide 79 text

fun dispatchStates(channel: ReceiveChannel>>) { launch { channel.consumeEach { reducer -> withContext(Dispatchers.Main) { dispatchState(reducer(state())) } } } } fun loadOrders() { store.dispatchStates(getOrders()) } Store

Slide 80

Slide 80 text

launch { channel.consumeEach { action -> withContext(Dispatchers.Main) { dispatchState(action(state())) } } } } fun loadOrders() { store.dispatchStates(getOrders()) }

Slide 81

Slide 81 text

class GetOrders @Inject constructor(private val repository: OrdersRepository) : Reducer() { operator fun invoke() = getOrders() private fun getOrders() : ReceiveChannel>> = produceActions { try { send { Either.Right(Success.Loading) } val orders = repository.allOrders() send { Either.Right(Orders(orders)) } } catch (e: Exception) { GetOrders

Slide 82

Slide 82 text

@Inject constructor(private val repository: OrdersRepository) : Reducer() { operator fun invoke() = getOrders() private fun getOrders() : ReceiveChannel>> = produceStates { try { send { Either.Right(Success.Loading) } val orders = repository.allOrders() send { Either.Right(Orders(orders)) } } catch (e: Exception) { send { Either.Left(OrdersFailure(e)) } } }

Slide 83

Slide 83 text

private fun getOrders() : ReceiveChannel>> = produceStates { try { send { Either.Right(Success.Loading) } val orders = repository.allOrders() send { Either.Right(Orders(orders)) } } catch (e: Exception) { send { Either.Left(OrdersFailure(e)) } } }

Slide 84

Slide 84 text

{ try { send { Either.Right(Success.Loading) } val orders = repository.allOrders() send { Either.Right(Orders(orders)) } } catch (e: Exception) { send { Either.Left(OrdersFailure(e)) } } }

Slide 85

Slide 85 text

Testing UI tests on Activity / Fragments 
 Unit + Integration tests on ViewModels Unit + instrumentation tests on Reducers

Slide 86

Slide 86 text

suspend inline fun ReceiveChannel>.states(initialState: T): List { return fold(emptyList()) { states, action -> states + action(states.lastOrNull() ?: initialState) } } ReducerTest

Slide 87

Slide 87 text

@Test fun `changes state on successful loading`() { val expectedState = Orders(listOf(ORDER_1, ORDER_2)) coEvery { ordersRepository.all() } returns listOf(ORDER_1, ORDER_2) val states = runBlocking { useCase.invoke().states(Either.Right(Success.Idle)) } assert(states).hasSize(2) assert(states[0]).isEqualTo(Either.Right(Success.Loading)) assert(states[1]).isEqualTo(Either.Right(expectedState)) } ReducerTest

Slide 88

Slide 88 text

@Test fun `changes state on error`() { val exception = IOException() coEvery { ordersRepository.allOrders() } throws exception val states = runBlocking { useCase.invoke().states(Either.Right(Success.Idle)) } assert(states).hasSize(2) assert(states[0]).isEqualTo(Either.Right(Success.Loading)) assert(states[1]).isEqualTo(Either.Left(OrdersFailure(exception))) } ReducerTest

Slide 89

Slide 89 text

What’s next? Explore Data Binding - Watch Jose’s talk This API will become obsolete in future updates with introduction of lazy asynchronous streams (https://github.com/Kotlin/kotlinx.coroutines/issues/254).

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

Thank you! David González @dggonzalez [email protected]

Slide 92

Slide 92 text

app/build.gradle buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.5.0' classpath 'com.getkeepsafe.dexcount:dexcount-gradle-plugin:0.2.1' } } ../build.gradle dependencies { compile 'com.android.support:herbs-v13:23.1.1' compile 'com.android.support:meat:23.1.1' compile ‘com.android.support:cookware-v7:23.1.1' compile ‘com.google.android.gms:play-services:8.4.0' }

Slide 93

Slide 93 text

CookingMethod cookingMethod = new CookingMethod.Builder() .withFlavour(Flavours.MediumRare) .withSide(Sides.Fries) .fromButcher(Butchers.GingerPig) .build(); private Steak from(CookingMethod cookingMethod){ Steak steak = Steak.from(cookingMethod.getButcher()); steak.addOil(new Oil()); steak.addSalt(new Salt()); steak.addPepper(new Pepper()); return steak; } Steak.java