Slide 1

Slide 1 text

@chris_h_codes Molecule Using Compose for presentation logic Chris Horner

Slide 2

Slide 2 text

Compose. Not Compose UI.

Slide 3

Slide 3 text

Presentation logic? MV Whatever Model Event

Slide 4

Slide 4 text

What does Molecule enable? @Composable fun models(events: Flow): Model { // Calculate Model here. } Why is this interesting?

Slide 5

Slide 5 text

2017

Slide 6

Slide 6 text

2017 RxJava

Slide 7

Slide 7 text

class MyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { button.setOnClickListener { } } } 2010

Slide 8

Slide 8 text

class MyActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { button.setOnClickListener { object : AsyncTask() { override fun doInBackground(vararg arg: Void?) { // Update "state" somehow? } } } } } 2010

Slide 9

Slide 9 text

<> Observable Observable Observable Observable The State of Managing State with RxJava https://youtu.be/0IKHxjkgop4 Jake Wharton 2017

Slide 10

Slide 10 text

2017 Single.just(input) .flatMap { longRunningOp(it) } .map { it.asSomethingElse() } .filter { someCheck(it) } .subscribe { … }

Slide 11

Slide 11 text

2017 Single.just(input) .flatMap { longRunningOp(it) } .map { it.asSomethingElse() } .filter { someCheck(it) } .subscribe { … } val result = longRunningOp(input) val output = result.asSomethingElse() return if someCheck(output) output else null

Slide 12

Slide 12 text

2017 Single.just(input) .flatMap { longRunningOp(it) } .map { it.asSomethingElse() } .filter { someCheck(it) } .subscribeOn(Schedulers.Io) .observeOn(Schedulers.Main) .subscribe { … } val result = longRunningOp(input) val output = result.asSomethingElse() return if someCheck(output) output else null

Slide 13

Slide 13 text

Single Maybe Completable suspend 2017

Slide 14

Slide 14 text

2019 fun map(mapper: (T) -> R): Flowable fun flatMapSingle(mapper: (T) -> SingleSource): Flowable Mapper Asynchronous Data Streams with Kotlin Flow https://youtu.be/tYcqn48SMT8 Roman Elizarov

Slide 15

Slide 15 text

2019 Sync Async fun map(mapper: (T) -> R): Flowable fun flatMapSingle(mapper: (T) -> SingleSource): Flowable Mapper Asynchronous Data Streams with Kotlin Flow https://youtu.be/tYcqn48SMT8 Roman Elizarov

Slide 16

Slide 16 text

fun map(mapper: (T) -> R): Flowable fun flatMapSingle(mapper: (T) -> SingleSource): Flowable Mapper 2019 fun filter(predicate: (T) -> Boolean): Flowable fun … 🤯 Predicate Sync Async Sync Async Asynchronous Data Streams with Kotlin Flow https://youtu.be/tYcqn48SMT8 Roman Elizarov Asynchronous Data Streams with Kotlin Flow https://youtu.be/tYcqn48SMT8 Roman Elizarov

Slide 17

Slide 17 text

flow.map { }

Slide 18

Slide 18 text

Operator Avoidance startWith(observable) startWith(value) delaySubscription(time) onStart { emitAll(flow) } onStart { emit(value) } onStart { delay(time) }

Slide 19

Slide 19 text

Operator Avoidance RxJava API surface Flow API surface

Slide 20

Slide 20 text

Operator Avoidance RxJava API surface Flow API surface

Slide 21

Slide 21 text

Operator Power val queries: Flowable sealed interface Model { object Loading : Model data class Loaded( val results: List ): Model }

Slide 22

Slide 22 text

Operator Power Mel val queries: Flowable sealed interface Model { object Loading : Model data class Loaded( val results: List ): Model }

Slide 23

Slide 23 text

Operator Power Mel val queries: Flowable sealed interface Model { object Loading : Model data class Loaded( val results: List ): Model }

Slide 24

Slide 24 text

Operator Power queries.switchMap { query - > search(query) .delaySubscription(300, TimeUnit.MILLISECONDS) .toObservable() .startWith { Model.Loading } }

Slide 25

Slide 25 text

Operator Power queries.switchMap { query - > search(query) .delaySubscription(300, TimeUnit.MILLISECONDS) .toObservable() .startWith { Model.Loading } } queries.transformLatest { query -> emit(Model.Loading) delay(300) emit(search(query)) }

Slide 26

Slide 26 text

Operator Power queries.switchMap { query - > search(query) .delaySubscription(300, TimeUnit.MILLISECONDS) .toObservable() .startWith { Model.Loading } } queries.transformLatest { query -> emit(Model.Loading) delay(300) emit(search(query)) } 1

Slide 27

Slide 27 text

Operator Power queries.switchMap { query - > search(query) .delaySubscription(300, TimeUnit.MILLISECONDS) .toObservable() .startWith { Model.Loading } } queries.transformLatest { query -> emit(Model.Loading) delay(300) emit(search(query)) } 2

Slide 28

Slide 28 text

Operator Power queries.switchMap { query - > search(query) .delaySubscription(300, TimeUnit.MILLISECONDS) .toObservable() .startWith { Model.Loading } } queries.transformLatest { query -> emit(Model.Loading) delay(300) emit(search(query)) } 3

Slide 29

Slide 29 text

Operator Power queries.switchMap { query - > search(query) .delaySubscription(300, TimeUnit.MILLISECONDS) .toObservable() .startWith { Model.Loading } } queries.transformLatest { query -> emit(Model.Loading) delay(300) emit(search(query)) } 1

Slide 30

Slide 30 text

Operator Power queries.switchMap { query - > search(query) .delaySubscription(300, TimeUnit.MILLISECONDS) .toObservable() .startWith { Model.Loading } } queries.transformLatest { query -> emit(Model.Loading) delay(300) emit(search(query)) } 2

Slide 31

Slide 31 text

Operator Power queries.switchMap { query - > search(query) .delaySubscription(300, TimeUnit.MILLISECONDS) .toObservable() .startWith { Model.Loading } } queries.transformLatest { query -> emit(Model.Loading) delay(300) emit(search(query)) } 3

Slide 32

Slide 32 text

So suspend + Flow wins. End of story? • suspend is great because we can write imperative code • Flow has advantages over Rx because it’s powered by coroutines • It still has many operators to learn • It’s still a slightly different way of writing code

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

queries.transformLatest { query -> emit(State.Loading) delay(300) emit(search(query)) }

Slide 35

Slide 35 text

queries .map { ... } .transformLatest { query -> emit(State.Loading) delay(300) emit(search(query)) } .flowOn( .. . ) .onEmpty { ... } .catch { .. . } .scan(emptyList()) { list, items -> list + items .map { ... } .zip() } .flatMapMerge(concurrency = 4) { .. . } .distinctUntilChanged()

Slide 36

Slide 36 text

What are we doing? We’re composing a model in response to events and values changing over time.

Slide 37

Slide 37 text

What if we actually used Compose to build that model? Molecule asks the question: What are we doing? We’re composing a model in response to events and values changing over time.

Slide 38

Slide 38 text

Column Text Row Column Image Text Text

Slide 39

Slide 39 text

Column Text Row Column Image Text Text @Composable fun UserInterface(model: Model) { }

Slide 40

Slide 40 text

Column Text Row Box Image Image Icon @Composable fun UserInterface(model: Model) { }

Slide 41

Slide 41 text

Column Text Row Image @Composable fun UserInterface(model: Model) { var someState: Int by remember { mutableStateOf(1) } } Box Image Icon

Slide 42

Slide 42 text

@Composable fun UserInterface(model: Model) { val someState: MutableState = remember { mutableStateOf(1) } }

Slide 43

Slide 43 text

@Composable fun UserInterface(model: Model) { val state: State } Reactive!

Slide 44

Slide 44 text

@Composable fun UserInterface(model: Model) { var someState: Int by remember { mutableStateOf(1) } }

Slide 45

Slide 45 text

@Composable fun UserInterface() { var someState: Int by remember { mutableStateOf(1) } LaunchedEffect(Unit) { while (true) { delay(1_000) someState ++ } } }

Slide 46

Slide 46 text

@Composable fun UserInterface() { var someState: Int by remember { mutableStateOf(1) } LaunchedEffect(Unit) { while (true) { delay(1_000) someState ++ } } Text(someState.toString()) }

Slide 47

Slide 47 text

@Composable fun UserInterface() { var someState: Int by remember { mutableStateOf(1) } LaunchedEffect(Unit) { while (true) { delay(1_000) someState ++ } } Text(someState.toString()) } Presentation logic

Slide 48

Slide 48 text

@Composable fun UserInterface() { } Flow Example

Slide 49

Slide 49 text

@Composable fun UserInterface() { } sealed interface Model { object Loading : Model data class Loaded( val results: List ) : Model }

Slide 50

Slide 50 text

@Composable fun UserInterface(queries: Flow) { }

Slide 51

Slide 51 text

@Composable fun UserInterface(queries: Flow) { val models = queries .onStart { emit("") } }

Slide 52

Slide 52 text

@Composable fun UserInterface(queries: Flow) { val models = queries .onStart { emit("") } .transformLatest { query -> emit(Model.Loading) } }

Slide 53

Slide 53 text

@Composable fun UserInterface(queries: Flow) { val models = queries .onStart { emit("") } .transformLatest { query -> emit(Model.Loading) delay(300) val results = search(query) emit(Model.Loaded(results)) } }

Slide 54

Slide 54 text

e terface(queries: Flow) { ls = queries rt { emit("") } formLatest { query -> (Model.Loading) y(300) results = search(query) (Model.Loaded(results)) interface Database { fun observeDataset(): Flow }

Slide 55

Slide 55 text

e terface(queries: Flow) { ls = queries rt { emit("") } formLatest { query -> (Model.Loading) y(300) results = search(query, dataset) (Model.Loaded(results)) interface Database { fun observeDataset(): Flow }

Slide 56

Slide 56 text

@Composable fun UserInterface(queries: Flow) { val models = queries .onStart { emit("") } .transformLatest { query -> emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results)) } }

Slide 57

Slide 57 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val models = queries .onStart { emit("") } .transformLatest { query -> emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results)) } }

Slide 58

Slide 58 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { combineTransform(queries, datasets) val models = queries .onStart { emit("") } .transformLatest { query -> emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results)) } } ?

Slide 59

Slide 59 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { combineTransformLatest(queries, dataset) val models = queries .onStart { emit("") } .transformLatest { query -> emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results)) } } ?

Slide 60

Slide 60 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val models = datasets.flatMapLatest { dataset -> queries .onStart { emit("") } .transformLatest { query - > emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results)) } } }

Slide 61

Slide 61 text

What if we used Compose?

Slide 62

Slide 62 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val models = datasets.flatMapLatest { dataset -> queries .onStart { emit("") } .transformLatest { query - > emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results)) } } } What if we used Compose?

Slide 63

Slide 63 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val query by queries.collectAsState("") val models = dataset s​ .flatMapLatest { dataset -> queries .onStart { emit("") } .transformLatest { query - > emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results)) } } }

Slide 64

Slide 64 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val query by queries.collectAsState("") val dataset by datasets.collectAsState(InitialSet) val models = dataset s​ .flatMapLatest { dataset -> queries .onStart { emit("") } .transformLatest { query - > emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results)) } } }

Slide 65

Slide 65 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val query by queries.collectAsState("") val dataset by datasets.collectAsState(InitialSet) var model by remember { mutableStateOf(Model.Loaded(emptyList())) } val models = dataset s​ .flatMapLatest { dataset -> queries .onStart { emit("") } .transformLatest { query - > emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results)) } } }

Slide 66

Slide 66 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val query by queries.collectAsState("") val dataset by datasets.collectAsState(InitialSet) var model by remember { mutableStateOf(Model.Loaded(emptyList())) } val models = dataset s​ .flatMapLatest { dataset -> queries .onStart { emit("") } .transformLatest { query - > emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results )​ ) } } }

Slide 67

Slide 67 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val query by queries.collectAsState("") val dataset by datasets.collectAsState(InitialSet) var model by remember { mutableStateOf(Model.Loaded(emptyList())) } LaunchedEffect(query, dataset) { emit(Model.Loading) delay(300) val results = search(query, dataset) emit(Model.Loaded(results )​ ) } }

Slide 68

Slide 68 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val query by queries.collectAsState("") val dataset by datasets.collectAsState(InitialSet) var model by remember { mutableStateOf(Model.Loaded(emptyList())) } LaunchedEffect(query, dataset) { model = Model.Loading delay(300) val results = search(query, dataset) model = Model.Loaded(results) } } Still reactive!

Slide 69

Slide 69 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { } • flatMap • scan • debounce • zip

Slide 70

Slide 70 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { } • remember • LaunchedEffect • collectAsState • mutableStateOf

Slide 71

Slide 71 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { } • remember • LaunchedEffect • collectAsState • mutableStateOf • if, else, when, for, while

Slide 72

Slide 72 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val query by queries.collectAsState("") val dataset by datasets.collectAsState(InitialSet) var model by remember { mutableStateOf(Model.Loaded(emptyList())) } LaunchedEffect(query, dataset) { model = Model.Loading delay(300) val results = search(query, dataset) model = Model.Loaded(results) } }

Slide 73

Slide 73 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val query by queries.collectAsState("") val dataset by datasets.collectAsState(InitialSet) var model by remember { mutableStateOf(Model.Loaded(emptyList())) } LaunchedEffect(query, dataset) { model = ​ Model.Loadin g​ delay(300) val results = search(query, dataset) model = ​ Model.Loaded(results) } Column { // .. . } }

Slide 74

Slide 74 text

@Composable fun UserInterface(queries: Flow, datasets: Flow) { val query by queries.collectAsState("") val dataset by datasets.collectAsState(InitialSet) var model by remember { mutableStateOf(Model.Loaded(emptyList())) } LaunchedEffect(query, dataset) { model = Model.Loading delay(300) val results = search(query, dataset) model = Model.Loaded(results) } Column { // .. . } } Presentation logic

Slide 75

Slide 75 text

Why do we need Molecule?

Slide 76

Slide 76 text

Why do we need Molecule? presentation-logic ui @Composable StateFlow junit

Slide 77

Slide 77 text

Why do we need Molecule? presentation-logic ui @Composable StateFlow junit

Slide 78

Slide 78 text

How do we use it?

Slide 79

Slide 79 text

How do we use it? apply plugin: 'app.cash.molecule'

Slide 80

Slide 80 text

How do we use it? Flow StateFlow

Slide 81

Slide 81 text

How do we use it? Flow StateFlow

Slide 82

Slide 82 text

How do we use it? val scope = CoroutineScope(AndroidUiDispatcher.Main)

Slide 83

Slide 83 text

How do we use it? val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { }

Slide 84

Slide 84 text

How do we use it? val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } }

Slide 85

Slide 85 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() } }

Slide 86

Slide 86 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() } model }

Slide 87

Slide 87 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() } model } 1

Slide 88

Slide 88 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() } model } 2

Slide 89

Slide 89 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() } model } 3 A Emissions

Slide 90

Slide 90 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() } model } 4 A Emissions

Slide 91

Slide 91 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() } model } 5 A Emissions

Slide 92

Slide 92 text

6 A B val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() } model } Emissions

Slide 93

Slide 93 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model } A B Emissions ?

Slide 94

Slide 94 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model } A B C Emissions

Slide 95

Slide 95 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { model } • Some State is invalidated • A MonotonicFrameClock ticks For a new emission, two things must happen Emissions

Slide 96

Slide 96 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model } A B C Emissions

Slide 97

Slide 97 text

A B C Emissions val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 98

Slide 98 text

A B C Frame tick Emissions val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 99

Slide 99 text

A B C Emissions val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 100

Slide 100 text

A B C Emissions C val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 101

Slide 101 text

A B C Emissions val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 102

Slide 102 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule() { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 103

Slide 103 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule( clock = RecompositionClock.ContextClock ) { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 104

Slide 104 text

val scope = CoroutineScope(AndroidUiDispatcher.Main) val models: StateFlow = scope.launchMolecule( clock = RecompositionClock.ContextClock ) { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 105

Slide 105 text

val scope = CoroutineScope (​ ) val models: StateFlow = scope.launchMolecule( clock = RecompositionClock.ContextClock ) { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 106

Slide 106 text

fun unitTest() = runBlocking { val scope = this val models: StateFlow = scope.launchMolecule( clock = RecompositionClock.ContextClock ) { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 107

Slide 107 text

fun unitTest() = runBlocking { val scope = this val models: StateFlow = scope.launchMolecule( clock = RecompositionClock.Immediate ) { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 108

Slide 108 text

fun unitTest() = runBlocking { val scope = this val models: StateFlow = scope.launchMolecule( clock = RecompositionClock.Immediate ) { var model by remember { mutableStateOf(Model(A)) } LaunchedEffect(Unit) { model = loadModelB() model = Model(C) } model }

Slide 109

Slide 109 text

ContextClock Immediate • Emissions match Android’s built in frame clock • Need to control emissions using BroadcastFrameClock • Unit tests requiring time manipulation Choosing a RecompositionClock • Frames tick automatically when snapshot state changes • Unit tests that don’t require time manipulation

Slide 110

Slide 110 text

You only get one emission per frame

Slide 111

Slide 111 text

Realistic example

Slide 112

Slide 112 text

Realistic example class Presenter { @Composable fun models(events: Flow): Model { // Calculate Model here. } }

Slide 113

Slide 113 text

Realistic example class Presenter { @Composable fun models(events: Flow): Model { // Calculate Model here. } }

Slide 114

Slide 114 text

class SearchPresenter : Presenter { @Composable fun models(events: Flow): Model { // Calculate Model here. } } Realistic example

Slide 115

Slide 115 text

sealed interface Event { data class EnterText(val text: String) : Event } sealed interface Model { object Loading : Model data class Loaded( val results: List = emptyList() ) : Model }

Slide 116

Slide 116 text

class SearchPresenter : Presenter { @Composable fun models(events: Flow): Model { // Calculate Model here. } } Realistic example

Slide 117

Slide 117 text

class SearchPresenter( val service: Service ) : Presenter { @Composable fun models(events: Flow): Model { // Calculate Model here. } } Realistic example

Slide 118

Slide 118 text

class SearchPresenter( val service: Service ) : Presenter { @Composable fun models(events: Flow): Model { val modelState = remember { mutableStateOf(Model.Loaded()) } } } Realistic example

Slide 119

Slide 119 text

class SearchPresenter( val service: Service ) : Presenter { @Composable fun models(events: Flow): Model { val modelState: MutableState = remember { mutableStateOf(Mod } } Realistic example

Slide 120

Slide 120 text

class SearchPresenter( val service: Service ) : Presenter { @Composable fun models(events: Flow): Model { val modelState = remember { mutableStateOf(Model.Loaded()) } } } Realistic example

Slide 121

Slide 121 text

class SearchPresenter( val service: Service ) : Presenter { @Composable fun models(events: Flow): Model { val modelState = remember { mutableStateOf(Model.Loaded()) } return modelState.value } } Realistic example

Slide 122

Slide 122 text

class SearchPresenter( val service: Service ) : Presenter { @Composable fun models(events: Flow): Model { val modelState = remember { mutableStateOf(Model.Loaded()) } LaunchedEffect(Unit) { events.collect { event -> when (event) { ... } } } return modelState.value } }

Slide 123

Slide 123 text

class SearchPresenter( val service: Service ) : Presenter { @Composable fun models(events: Flow): Model { val modelState = remember { mutableStateOf(Model.Loaded()) } var query by remember { mutableStateOf("") } LaunchedEffect(Unit) { events.collect { event -> when (event) { EnterText -> query = event.text } } } return modelState.value }

Slide 124

Slide 124 text

@Composable fun models(events: Flow): Model { val modelState = remember { mutableStateOf(Model.Loaded()) } var query by remember { mutableStateOf("") } LaunchedEffect(Unit) { events.collect { event -> when (event) { EnterText -> query = event.text } } } LaunchedEffect(query) { runSearch(query, modelState) } return modelState.value }

Slide 125

Slide 125 text

private suspend fun runSearch( query: String, state: MutableState, ) { state.value = Model.Loading val results = service.search(query) state.value = Model.Loaded(results) } LaunchedEffect(query) { runSearch(query, modelState) }

Slide 126

Slide 126 text

private suspend fun runSearch( query: String, state: MutableState, ) { state.value = Model.Loading val results = service.search(query) state.value = Model.Loaded(results) } LaunchedEffect(query) { runSearch(query, modelState) }

Slide 127

Slide 127 text

private suspend fun runSearch( query: String, state: MutableState, ) { state.value = Model.Loading val results = service.search(query) state.value = Model.Loaded(results) } LaunchedEffect(query) { runSearch(query, modelState) }

Slide 128

Slide 128 text

Writing a test cashapp/turbine

Slide 129

Slide 129 text

cashapp/turbine Writing a test flowOf("one", "two").test { assertEquals("one", awaitItem()) assertEquals("two", awaitItem()) awaitComplete() }

Slide 130

Slide 130 text

Writing a test @Test fun `entering text runs search`() = runBlocking { }

Slide 131

Slide 131 text

Writing a test @Test fun `entering text runs search`() = runBlocking { val events = MutableSharedFlow(replay = 1) }

Slide 132

Slide 132 text

Writing a test @Test fun `entering text runs search`() = runBlocking { val events = MutableSharedFlow(replay = 1) launchMolecule(RecompositionClock.Immediate) { presenter.models(events) }.test { } }

Slide 133

Slide 133 text

Writing a test @Test fun `entering text runs search`() = runBlocking { val events = MutableSharedFlow(replay = 1) launchMolecule(RecompositionClock.Immediate) { presenter.models(events) }.test { assertThat(awaitItem()).isEqualTo(Model.Loading) } }

Slide 134

Slide 134 text

Writing a test @Test fun `entering text runs search`() = runBlocking { val events = MutableSharedFlow(replay = 1) launchMolecule(RecompositionClock.Immediate) { presenter.models(events) }.test { assertThat(awaitItem()).isEqualTo(Model.Loading) events.emit(Event.EnterText("query")) fakeService.setResults( .. . ) } }

Slide 135

Slide 135 text

Writing a test @Test fun `entering text runs search`() = runBlocking { val events = MutableSharedFlow(replay = 1) launchMolecule(RecompositionClock.Immediate) { presenter.models(events) }.test { assertThat(awaitItem()).isEqualTo(Model.Loading) events.emit(Event.EnterText("query")) fakeService.setResults( .. . ) assertThat(awaitItem()).isEqualTo(Model.Loaded( .. . )) } }

Slide 136

Slide 136 text

Writing a test @Test fun `entering text runs search`() = runBlocking { presenter.test { assertThat(awaitItem()).isEqualTo(Model.Loading) sendEvent(Event.EnterText("query")) fakeService.setResults( .. . ) assertThat(awaitItem()).isEqualTo(Model.Loaded( .. . )) } }

Slide 137

Slide 137 text

Takeaways

Slide 138

Slide 138 text

Takeaways • Compose manages a tree of nodes - it doesn’t have to be UI • Managing state involves tying together streams • Compose can do to streams what suspend did to Single • State is reactive. Think of it like a stream • There’s still a learning curve, but it’s less steep compared to Rx/Flow • Tricks you’ve learnt in Compose UI work in Molecule too

Slide 139

Slide 139 text

Interested in more? Building StateFlows with Jetpack Compose droidcon.com/2022/09/29/building-stateflows-in-android-with-jetpack-compose Mohit Sarveiya Demystifying Molecule droidcon.com/2022/09/29/demystifying-molecule-running-your-own-compositions-for-fun-and-profit Bill Phillips & Ash Davies Opening the Shutter on Snapshots droidcon.com/2022/09/29/opening-the-shutter-on-snapshots Zach Klippenstein

Slide 140

Slide 140 text

chris_h_codes github.com/cashapp/molecule Molecule Using Compose for presentation logic