Slide 1

Slide 1 text

Mohit Sarveiya Dissecting Coroutines Library @heyitsmohit

Slide 2

Slide 2 text

Dissecting Coroutines Library ● Context ● Channels ● Flows ● Shared Mutable State

Slide 3

Slide 3 text

Dissecting Coroutines Library ● Implementation ● Use cases

Slide 4

Slide 4 text

Context

Slide 5

Slide 5 text

val scope = CoroutineScope(Dispatchers.IO) scope.launch { }

Slide 6

Slide 6 text

val scope = CoroutineScope(Dispatchers.IO) fun CoroutineScope(context: CoroutineContext)

Slide 7

Slide 7 text

interface CoroutineContext { interface Key interface Element }

Slide 8

Slide 8 text

interface CoroutineContext { interface Key interface Element }

Slide 9

Slide 9 text

interface CoroutineContext { operator fun get(key: Key): E? operator fun plus(context: CoroutineContext): CoroutineContext }

Slide 10

Slide 10 text

interface CoroutineContext { operator fun get(key: Key): E? operator fun plus(context: CoroutineContext) }

Slide 11

Slide 11 text

Context Elements ● Job ● Coroutine Name ● Dispatcher

Slide 12

Slide 12 text

val scope = CoroutineScope( CoroutineName("My Coroutine") + Dispatchers.IO )

Slide 13

Slide 13 text

val scope = CoroutineScope( CoroutineName("My Coroutine") + Dispatchers.IO ) operator fun plus(context: CoroutineContext)

Slide 14

Slide 14 text

val scope = CoroutineScope( CoroutineName("My Coroutine") + Dispatchers.IO ) scope.coroutineContext[CoroutineName]

Slide 15

Slide 15 text

val scope = CoroutineScope( CoroutineName("My Coroutine") + Dispatchers.IO ) scope.coroutineContext[CoroutineName] / / CoroutineName(My Coroutine)

Slide 16

Slide 16 text

val scope = CoroutineScope( CoroutineName("My Coroutine") + Dispatchers.IO ) scope.coroutineContext[ContinuationInterceptor]

Slide 17

Slide 17 text

val job = Job() val scope = CoroutineScope( CoroutineName("My Coroutine") + job + Dispatchers.IO )

Slide 18

Slide 18 text

val job = Job() val scope = CoroutineScope( CoroutineName("My Coroutine") + job + Dispatchers.IO )

Slide 19

Slide 19 text

val job = Job() val scope = CoroutineScope( CoroutineName("My Coroutine") + job + Dispatchers.IO ) scope.coroutineContext[Job] / / JobImpl{Active}

Slide 20

Slide 20 text

Custom Context Use Cases ● Dispatcher Provider (Dispatch) ● Thread Local (krotoPlus) ● Database Transactions (Room)

Slide 21

Slide 21 text

RBusarow/Dispatch Code ! Issues Pull Requests Dispatch Bazel Build passing Gradle Build passing Utilities for kotlinx.coroutines which make them type-safe, easier to test, and more expressive.

Slide 22

Slide 22 text

Scopes ● IOScope ● DefaultScope ● UnDispatchedScope

Slide 23

Slide 23 text

class DefaultDispatcherProvider { val default: CoroutineDispatcher = Dispatchers.Default val io: CoroutineDispatcher = Dispatchers.IO val main: CoroutineDispatcher = Dispatchers.Main }

Slide 24

Slide 24 text

interface DispatcherProvider : CoroutineContext.Element { override val key: CoroutineContext.Key < * > get() = Key companion object Key : CoroutineContext.Key }

Slide 25

Slide 25 text

fun IOCoroutineScope(dispatcherProvider = DefaultDispatcherProvider()) { override val coroutineContext = job + dispatcherProvider.io + dispatcherProvider }

Slide 26

Slide 26 text

Resources ● Custom Coroutine Context Use Cases ● Dispatch

Slide 27

Slide 27 text

Channels

Slide 28

Slide 28 text

Coroutine Coroutine Channel

Slide 29

Slide 29 text

Coroutine Coroutine Data Channel

Slide 30

Slide 30 text

interface Channel { suspend fun send(element: E) suspend fun receive(): E } Channel

Slide 31

Slide 31 text

Channel Types ● Rendezvous ● Buffered ● Unlimited

Slide 32

Slide 32 text

fun Channel(capacity: Int = RENDEZVOUS) = when (capacity) { RENDEZVOUS - > RendezvousChannel() UNLIMITED - > LinkedListChannel() CONFLATED - > ConflatedChannel() BUFFERED - > ArrayChannel(CHANNEL_DEFAULT_CAPACITY) else - > ArrayChannel(capacity) }

Slide 33

Slide 33 text

Channel Types ● Rendezvous ● Buffered ● Unlimited

Slide 34

Slide 34 text

runBlocking { 
 val channel = Channel() launch { channel.send(1) } val num = channel.receive() }

Slide 35

Slide 35 text

runBlocking { 
 val channel = Channel() launch { channel.send(1) } val num = channel.receive() }

Slide 36

Slide 36 text

runBlocking { 
 val channel = Channel() launch { channel.send(1) } val num = channel.receive() }

Slide 37

Slide 37 text

runBlocking { 
 val channel = Channel() launch { channel.send(1) } val num = channel.receive() } SUSPEND

Slide 38

Slide 38 text

runBlocking { 
 val channel = Channel() launch { channel.send(1) } val num = channel.receive() }

Slide 39

Slide 39 text

Channel Types ● Rendezvous ● Buffered ● Unlimited

Slide 40

Slide 40 text

runBlocking { 
 val channel = Channel(10) launch { channel.send(1) } val num = channel.receive() }

Slide 41

Slide 41 text

runBlocking { 
 val channel = Channel(10) launch { channel.send(1) channel.send(2) channel.send(3) } }

Slide 42

Slide 42 text

Channel Types ● Rendezvous ● Buffered ● Unlimited

Slide 43

Slide 43 text

runBlocking { 
 val channel = Channel(Channel.UNLIMITED) launch { channel.send(1) channel.send(2) channel.send(3) } }

Slide 44

Slide 44 text

runBlocking { 
 val channel = Channel(Channel.UNLIMITED) launch { channel.send(1) channel.send(2) channel.send(3) } }

Slide 45

Slide 45 text

Channel Types ● Rendezvous ● Buffered ● Unlimited

Slide 46

Slide 46 text

Papers

Slide 47

Slide 47 text

Channel State ● Queue ● Optional Buffer

Slide 48

Slide 48 text

Channel Queue States ● Empty ● Send Queued ● Send Buffered ● Closed

Slide 49

Slide 49 text

Channel Queue States Lock Free Linked List Node Empty Queue Send Buffered Send Queued Closed

Slide 50

Slide 50 text

val channel = Channel() Queue Empty Queue

Slide 51

Slide 51 text

val channel = Channel() channel.send(1)

Slide 52

Slide 52 text

class SendElement( val data: Any?, val cont: CancellableContinuation ) : LockFreeLinkedListNode()

Slide 53

Slide 53 text

val channel = Channel() channel.send(1) Queue Send Element(1)

Slide 54

Slide 54 text

val channel = Channel() channel.send(1) channel.receive() Queue Empty Queue

Slide 55

Slide 55 text

val channel = Channel() channel.send(1) println(channel)

Slide 56

Slide 56 text

val channel = Channel() channel.send(1) println(channel) / / RendezvousChannel{SendQueued}

Slide 57

Slide 57 text

class AbstractSendChannel { fun toString() = {$queueDebugStateString}$bufferDebugString” } Query Channel State

Slide 58

Slide 58 text

class AbstractSendChannel { fun toString() = {$queueDebugStateString}$bufferDebugString” } Query Channel State

Slide 59

Slide 59 text

$queueDebugStateString get() { 
 when (head) { 
 is Closed < * > - > head.toString() 
 is Receive < * > - > "ReceiveQueued" 
 is Send - > "SendQueued" else - > "UNEXPECTED:$head" } } Query Channel State

Slide 60

Slide 60 text

$queueDebugStateString get() { 
 when (head) { 
 is Closed < * > - > head.toString() 
 is Receive < * > - > "ReceiveQueued" 
 is Send - > "SendQueued" else - > "UNEXPECTED:$head" } } Query Channel State

Slide 61

Slide 61 text

$queueDebugStateString get() { 
 when (head) { 
 is Closed < * > - > head.toString() 
 is Receive < * > - > "ReceiveQueued" 
 is Send - > "SendQueued" else - > "UNEXPECTED:$head" } } Query Channel State

Slide 62

Slide 62 text

$queueDebugStateString get() { 
 when (head) { 
 is Closed < * > - > head.toString() 
 is Receive < * > - > "ReceiveQueued" 
 is Send - > "SendQueued" else - > "UNEXPECTED:$head" } } Query Channel State

Slide 63

Slide 63 text

$queueDebugStateString get() { 
 when (head) { 
 is Closed < * > - > head.toString() 
 is Receive < * > - > "ReceiveQueued" 
 is Send - > "SendQueued" else - > "UNEXPECTED:$head" } } Query Channel State

Slide 64

Slide 64 text

val channel = Channel() channel.send(1) println(channel) / / RendezvousChannel{SendQueued} Query Channel State

Slide 65

Slide 65 text

runBlocking { 
 val channel = Channel(10) launch { channel.send(1) channel.send(2) channel.send(3) } }

Slide 66

Slide 66 text

runBlocking { 
 val channel = Channel(10) launch { channel.send(1) channel.send(2) channel.send(3) println(channel) } }

Slide 67

Slide 67 text

runBlocking { 
 val channel = Channel(10) launch { channel.send(1) channel.send(2) channel.send(3) println(channel) } } / / BufferedChannel{SendQueued}{3}

Slide 68

Slide 68 text

fun CoroutineScope.producer(): ReceiveChannel = 
 produce { for (i in 1 . . 5) { send(i) } }

Slide 69

Slide 69 text

fun CoroutineScope.producer(): ReceiveChannel = 
 produce { for (i in 1 . . 5) { send(i) } }

Slide 70

Slide 70 text

fun CoroutineScope.producer(): ReceiveChannel = 
 produce { for (i in 1 . . 5) { send(i) } close() }

Slide 71

Slide 71 text

runBlocking { 
 val channel: ReceiveChannel = producer() for (num in channel) { calculate(num) } }

Slide 72

Slide 72 text

runBlocking { 
 val channel: ReceiveChannel = producer() for (num in channel) { } }

Slide 73

Slide 73 text

interface ChannelIterator { suspend fun hasNextSuspend(): E fun next(): E } Channel Iterator

Slide 74

Slide 74 text

Coroutine A EmptyQueue Channel Queue Coroutine B

Slide 75

Slide 75 text

Coroutine A SendElement(1) Channel Queue Coroutine B 1

Slide 76

Slide 76 text

Coroutine A SendElement(1) Channel Queue Coroutine B 1 hasNext()

Slide 77

Slide 77 text

Coroutine A SendElement(1) Channel Queue Coroutine B 1 next()

Slide 78

Slide 78 text

Coroutine A SendElement(1) Channel Queue Coroutine B 1 next()

Slide 79

Slide 79 text

Coroutine A SendElement(1) Channel Queue Coroutine B 1 next() 2 3

Slide 80

Slide 80 text

Coroutine A SendElement(1) Channel Queue Coroutine B 1 2 3 X

Slide 81

Slide 81 text

runBlocking { 
 val channel: ReceiveChannel = producer() for (num in channel) { } }

Slide 82

Slide 82 text

Papers

Slide 83

Slide 83 text

Channels ● Implementation ● Use cases

Slide 84

Slide 84 text

marcoferrer/kroto-plus Code ! Issues Pull Requests Kroto-Plus+ - An RPC library and framework Bazel Build passing Gradle Build passing A Kotlin/JVM implementation of gRPC: A high performance, open source, general RPC framework that puts mobile and HTTP/2 first.

Slide 85

Slide 85 text

Server gRPC

Slide 86

Slide 86 text

Server gRPC service

Slide 87

Slide 87 text

Server(Go) gRPC service Client(Java) Client(Python) Client(Javascript) service service service

Slide 88

Slide 88 text

Server(Go) gRPC service Client(Java) Client(Python) Client(Javascript)

Slide 89

Slide 89 text

Server(Go) gRPC service Client(Java) Client(Python) Client(Javascript) call call call

Slide 90

Slide 90 text

Server(Go) gRPC service Client(Java) Client(Python) Client(Javascript) call call call HTTP 2

Slide 91

Slide 91 text

Channels with gRPC Client Server Scope (Dispatcher) Request Send Channel Receive Channel

Slide 92

Slide 92 text

Client Server Scope (Dispatcher) Request Send Channel Receive Channel Channels with gRPC

Slide 93

Slide 93 text

Client Server Scope (Dispatcher) Response Send Channel Receive Channel Channels with gRPC

Slide 94

Slide 94 text

Resources ● Lock-free algorithms for Kotln Corotuines (Part 1) ● Lock-free algorithms for Kotln Corotuines (Part 2) ● gRPC with Kotlin Coroutines

Slide 95

Slide 95 text

Flows

Slide 96

Slide 96 text

Coroutine Coroutine Flow

Slide 97

Slide 97 text

Coroutine Coroutine Flow

Slide 98

Slide 98 text

val flow = flowOf(1,2,3)

Slide 99

Slide 99 text

val flow = flowOf(1,2,3) flow.collect { println(it) }

Slide 100

Slide 100 text

val flow = flow { emit(1) delay(2000) emit(1) }

Slide 101

Slide 101 text

flow .filter { } .map { } .combine(flow2) { }

Slide 102

Slide 102 text

flow .filter { } .map { } .combine(flow2) { } .flowOn(Dispatchers.IO)

Slide 103

Slide 103 text

flow.collect { }

Slide 104

Slide 104 text

flow.launchIn(scope)

Slide 105

Slide 105 text

fun Flow.launchIn(scope: CoroutineScope): Job = scope.launch { collect() }

Slide 106

Slide 106 text

val value = flow.single()

Slide 107

Slide 107 text

Bridge to Flow

Slide 108

Slide 108 text

apollographql/apollo-android Code ! Issues Pull Requests Apollo Android Bazel Build passing Gradle Build passing Apollo Android is a GraphQL client that generates Java and Kotlin models from GraphQL queries.

Slide 109

Slide 109 text

val client = ApolloClient.builder() .serverUrl(“url") .build()

Slide 110

Slide 110 text

client.query(query).enqueue( object : ApolloCall.Callback() { override fun onResponse(response: Response) { } override fun onFailure(e: ApolloException) { } override fun onStatusEvent(event: ApolloCall.StatusEvent) { } })

Slide 111

Slide 111 text

client.query(query).enqueue( object : ApolloCall.Callback() { override fun onResponse(response: Response) { } override fun onFailure(e: ApolloException) { } override fun onStatusEvent(event: ApolloCall.StatusEvent) { } })

Slide 112

Slide 112 text

Callback Flow ● Coroutine on Produce Scope ● Provides a channel to send

Slide 113

Slide 113 text

callbackFlow { }

Slide 114

Slide 114 text

callbackFlow { enqueue( object : ApolloCall.Callback() { override fun onResponse(response: Response) { offer(response) } override fun onFailure(e: ApolloException) { close(e) } override fun onStatusEvent(event: ApolloCall.StatusEvent) { if (event = = ApolloCall.StatusEvent.COMPLETED) { close() } }

Slide 115

Slide 115 text

callbackFlow { enqueue( object : ApolloCall.Callback() { override fun onResponse(response: Response) { offer(response) } override fun onFailure(e: ApolloException) { close(e) } override fun onStatusEvent(event: ApolloCall.StatusEvent) { if (event = = ApolloCall.StatusEvent.COMPLETED) { close() } }

Slide 116

Slide 116 text

callbackFlow { enqueue( object : ApolloCall.Callback() { override fun onResponse(response: Response) { offer(response) } override fun onFailure(e: ApolloException) { close(e) } override fun onStatusEvent(event: ApolloCall.StatusEvent) { if (event = = ApolloCall.StatusEvent.COMPLETED) { close() } }

Slide 117

Slide 117 text

callbackFlow { enqueue( object : ApolloCall.Callback() { override fun onResponse(response: Response) { offer(response) } override fun onFailure(e: ApolloException) { close(e) } override fun onStatusEvent(event: ApolloCall.StatusEvent) { if (event = = ApolloCall.StatusEvent.COMPLETED) { close() } }

Slide 118

Slide 118 text

callbackFlow { 
 enqueue( . . . ) 
 awaitClose { cancel() } }

Slide 119

Slide 119 text

fun ApolloCall.toFlow() { callbackFlow { 
 enqueue( . . . ) 
 awaitClose { [email protected]() } } }

Slide 120

Slide 120 text

val flow = client.query(query).toFlow()

Slide 121

Slide 121 text

Combine

Slide 122

Slide 122 text

1 2 3 1s 1s

Slide 123

Slide 123 text

1 2 3 1s 1s val numbersFlow = flowOf(1,2,3) .onEach { delay(1000) }

Slide 124

Slide 124 text

A B C 2s 2s

Slide 125

Slide 125 text

A B C 2s 2s val lettersFlow = flowOf("A", “B","C") .onEach { delay(2000) }

Slide 126

Slide 126 text

1 2 3 A B C 1s 1s 2s 2s Combine

Slide 127

Slide 127 text

numbersFlow.combine(lettersFlow) { number, letter - > }

Slide 128

Slide 128 text

numbersFlow.combine(lettersFlow) { number, letter - > "$number$letter" }

Slide 129

Slide 129 text

1 2 3 A B C 1s 1s 2s 2s 1A 2A 3C 3A 3B

Slide 130

Slide 130 text

numbersFlow.combine(lettersFlow) { number, letter - > "$number$letter" }.collect { println(it) }

Slide 131

Slide 131 text

numbersFlow.combine(lettersFlow) { number, letter - > "$number$letter" }.collect { print(it) } HelloWorld.kt 1A 2A 3A 3B 3C

Slide 132

Slide 132 text

1 2 3 A B C 1s 1s 2s 2s How did combine work?

Slide 133

Slide 133 text

1.4.x 1.3.x Zip, Combine Implementation Evolution Selectors New Version

Slide 134

Slide 134 text

Selectors

Slide 135

Slide 135 text

Send Send Channel A Channel B

Slide 136

Slide 136 text

Send Send Channel A Channel B

Slide 137

Slide 137 text

Send Send Channel A Channel B Receive

Slide 138

Slide 138 text

Send Channel A Channel B Send Receive

Slide 139

Slide 139 text

Channel B Send Receive Channel A Send Receive Read simultaneously from both channels?

Slide 140

Slide 140 text

fun CoroutineScope.hello() = produce { while (true) { delay(300) send("Hello") } } Send Hello

Slide 141

Slide 141 text

fun CoroutineScope.world() = produce { while (true) { delay(500) send("World!") } } Send World!

Slide 142

Slide 142 text

val receiveChannel = hello() 
 fun CoroutineScope.hello() = produce { while (true) { delay(300) send("Hello") } } Send Hello

Slide 143

Slide 143 text

val receiveChannel = hello() receiveChannel.receive() 
 fun CoroutineScope.hello() = produce { while (true) { delay(300) send("Hello") } } Send Receive

Slide 144

Slide 144 text

Channel B Send Receive Channel A Send Receive Read simultaneously from both channels?

Slide 145

Slide 145 text

suspend fun selectHelloWorld(channelA, channelB) { }

Slide 146

Slide 146 text

suspend fun selectHelloWorld(channelA, channelB) { select { } } Selector

Slide 147

Slide 147 text

suspend fun selectHelloWorld(channelA, channelB) { select { } } Return

Slide 148

Slide 148 text

interface ReceiveChannel { onReceive: SelectClause1 val onReceiveOrNull: SelectClause1 onReceiveOrClosed: SelectClause1 }

Slide 149

Slide 149 text

suspend fun selectHelloWorld(channelA, channelB) { select { channelA.onReceive { value - > } } }

Slide 150

Slide 150 text

suspend fun selectHelloWorld(channelA, channelB) { select { channelA.onReceive { value - > } channelB.onReceive { value - > } } }

Slide 151

Slide 151 text

suspend fun selectHelloWorld(channelA, channelB) { select { channelA.onReceive { value - > println(value) } channelB.onReceive { value - > println(value) } } }

Slide 152

Slide 152 text

val channelA = hello() val channelB = world() selectHelloWorld(channelA, channelB)

Slide 153

Slide 153 text

fun CoroutineScope.hello() = produce { while (true) { delay(300) send("Hello") } } selectHelloWorld(channelA, channelB)

Slide 154

Slide 154 text

fun CoroutineScope.hello() = produce { while (true) { delay(300) send("Hello") } } selectHelloWorld(channelA, channelB)

Slide 155

Slide 155 text

suspend fun selectHelloWorld(channelA, channelB) { select { channelA.onReceive { value - > println(value) } channelB.onReceive { value - > println(value) } } } / / Hello

Slide 156

Slide 156 text

val channelA = hello() val channelB = world() selectHelloWorld(channelA, channelB) selectHelloWorld(channelA, channelB)

Slide 157

Slide 157 text

fun CoroutineScope.world() = produce { while (true) { delay(500) send("World!") } } selectHelloWorld(channelA, channelB)

Slide 158

Slide 158 text

fun CoroutineScope.world() = produce { while (true) { delay(500) send("World!") } } selectHelloWorld(channelA, channelB)

Slide 159

Slide 159 text

suspend fun selectHelloWorld(channelA, channelB) { select { channelA.onReceive { value - > println(value) } channelB.onReceive { value - > println(value) } } } / / World!

Slide 160

Slide 160 text

val channelA = hello() val channelB = world() Close

Slide 161

Slide 161 text

interface ReceiveChannel { onReceive: SelectClause1 val onReceiveOrNull: SelectClause1 onReceiveOrClosed: SelectClause1 }

Slide 162

Slide 162 text

suspend fun selectHelloWorld(channelA, channelB) { select { channelA.onReceiveOrNull { value - > } channelB.onReceiveOrNull { value - > } } }

Slide 163

Slide 163 text

suspend fun selectHelloWorld(channelA, channelB) { select { channelA.onReceiveOrNull { value - > } channelB.onReceiveOrNull { value - > } } } Null when channelA closed

Slide 164

Slide 164 text

Channel B Send Receive Channel A Send Receive Read simultaneously from both channels Selectors

Slide 165

Slide 165 text

1 2 3 A B C 1s 1s 2s 2s Combine

Slide 166

Slide 166 text

1 2 3 Send Channel A

Slide 167

Slide 167 text

1 2 3 Send Channel A

Slide 168

Slide 168 text

A B C Send Channel B

Slide 169

Slide 169 text

A B C Send Channel B

Slide 170

Slide 170 text

Send Channel B Send Channel A Selector A 1

Slide 171

Slide 171 text

Send Channel B Send Channel A Selector A 1

Slide 172

Slide 172 text

Send Channel B Send Channel A Selector A 1 Transform

Slide 173

Slide 173 text

Send Channel B Send Channel A Selector A 1

Slide 174

Slide 174 text

1 2 3 A B C 1A 2A

Slide 175

Slide 175 text

Send Channel B Send Channel A Selector A

Slide 176

Slide 176 text

1 2 3 A B C 1A 2A

Slide 177

Slide 177 text

Send Channel B Send Channel A Selector A

Slide 178

Slide 178 text

Send Channel B Send Channel A Selector A 2

Slide 179

Slide 179 text

Send Channel B Send Channel A Selector A 2

Slide 180

Slide 180 text

Send Channel B Send Channel A Selector A 2

Slide 181

Slide 181 text

suspend fun combine( first: Flow, second: Flow, transform: suspend FlowCollector.(a: T1, b: T2) - > Unit ) { }

Slide 182

Slide 182 text

suspend fun combine( first: Flow, second: Flow, transform: suspend FlowCollector.(a: T1, b: T2) - > Unit ) { }

Slide 183

Slide 183 text

suspend fun combine( . . . ) { val firstChannel = createChannel(firstFlow) val secondChannel = createChannel(secondFlow) }

Slide 184

Slide 184 text

suspend fun combine( . . . ) { val firstChannel = createChannel(firstFlow) val secondChannel = createChannel(secondFlow) var firstValue: Any? = null var secondValue: Any? = null }

Slide 185

Slide 185 text

suspend fun combine( . . . ) { val firstChannel = createChannel(firstFlow) val secondChannel = createChannel(secondFlow) var firstValue: Any? = null var secondValue: Any? = null var firstIsClosed = false var secondIsClosed = false }

Slide 186

Slide 186 text

suspend fun combine( . . . ) { while (!firstIsClosed | | !secondIsClosed) { } }

Slide 187

Slide 187 text

suspend fun combine( . . . ) { while (!firstIsClosed | | !secondIsClosed) { select { } } }

Slide 188

Slide 188 text

select { channelA.onReceive { value - > firstValue = value if (secondValue ! = = null) { transform( . . . ) } } channelB.onReceive { value - > secondValue = value if (secondValue ! = = null) { transform( . . . ) } }

Slide 189

Slide 189 text

select { channelA.onReceive { value - > firstValue = value if (secondValue ! = = null) { transform( . . . ) } } channelB.onReceive { value - > secondValue = value if (firstValue ! = = null) { transform( . . . ) } }

Slide 190

Slide 190 text

1 2 3 A B C 1s 1s 2s 2s Combine

Slide 191

Slide 191 text

Shared Flow

Slide 192

Slide 192 text

val channel = ConflatedBroadcastChannel(10)

Slide 193

Slide 193 text

val channel = ConflatedBroadcastChannel(10) channel.send(1) channel.send(2) / / Conflate previously sent

Slide 194

Slide 194 text

val channel = ConflatedBroadcastChannel(10) channel.send(1) channel.send(2) / / Conflate previously sent channel.close()

Slide 195

Slide 195 text

Shared Flow ● Mutable State Flow ● Mutable Shared Flow

Slide 196

Slide 196 text

View View Model State

Slide 197

Slide 197 text

class MyViewModel(): ViewModel() { } Jetpack View Model

Slide 198

Slide 198 text

val ViewModel.viewModelScope: CoroutineScope get() { return setTagIfAbsent(JOB_KEY, CloseableCoroutineScope( 
 SupervisorJob() + Dispatchers.Main.immediate) 
 ) }

Slide 199

Slide 199 text

class MyViewModel(): ViewModel() { val states = MutableStateFlow(State()) } State Flow

Slide 200

Slide 200 text

class MyViewModel(): ViewModel() { val states = MutableStateFlow(State()) fun updateState() { flowOfData .map { mapToState(data) } .onEach { state - > states.value = state } .launchIn(viewModelScope) } }

Slide 201

Slide 201 text

class MyViewModel(): ViewModel() { val states = MutableStateFlow(State()) fun updateState() { flowOfData .map { mapToState(data) } .onEach { state - > states.value = state } .launchIn(viewModelScope) } }

Slide 202

Slide 202 text

class MyViewModel(): ViewModel() { val states = MutableStateFlow(State()) fun updateState() { flowOfData .map { mapToState(data) } .onEach { state - > states.value = state } .launchIn(viewModelScope) } }

Slide 203

Slide 203 text

class MyViewModel(): ViewModel() { val states = MutableStateFlow(State()) fun updateState() { flowOfData .map { mapToState(data) } .collect { state - > 
 states.value = state } / / logic after collect will run after it finishes } } Suspending

Slide 204

Slide 204 text

class MyViewModel(): ViewModel() { val states = MutableStateFlow(State()) fun updateState() { flowOfData .map { mapToState(data) } .onEach { state - > states.value = state } .launchIn(viewModelScope) } }

Slide 205

Slide 205 text

class MyViewModel(): ViewModel() { val states = MutableSharedFlow() fun updateState() { flowOfData .map { mapToState(data) } .onEach { state - > states.value = state } .launchIn(viewModelScope) } }

Slide 206

Slide 206 text

class MyViewModel(): ViewModel() { val states = MutableSharedFlow() fun updateState() { flowOfData .map { mapToState(data) } .onEach { state - > states.emit(data) } .launchIn(viewModelScope) } }

Slide 207

Slide 207 text

Mutable State

Slide 208

Slide 208 text

State

Slide 209

Slide 209 text

State Coroutine Coroutine Coroutine

Slide 210

Slide 210 text

State Coroutine Coroutine Coroutine

Slide 211

Slide 211 text

Mutable State ● Mutex ● Actor

Slide 212

Slide 212 text

var counter = 0 suspend fun CoroutineScope.updateState() { }

Slide 213

Slide 213 text

var counter = 0 suspend fun CoroutineScope.updateState() { val jobs = List(100) { launch { } } }

Slide 214

Slide 214 text

var counter = 0 suspend fun CoroutineScope.updateState() { val jobs = List(100) { launch { repeat(1000) { counter + + } } } }

Slide 215

Slide 215 text

var counter = 0 updateState()

Slide 216

Slide 216 text

var counter = 0 updateState() println(counter) / / 71906

Slide 217

Slide 217 text

var counter = 0 updateState() println(counter) / / 56467

Slide 218

Slide 218 text

Mutex

Slide 219

Slide 219 text

public interface Mutex { val isLocked: Boolean suspend fun lock() fun unlock() }

Slide 220

Slide 220 text

var counter = 0 suspend fun CoroutineScope.updateState() { val jobs = List(100) { launch { repeat(1000) { counter + + } } } }

Slide 221

Slide 221 text

var mutext = Mutex() var counter = 0 suspend fun CoroutineScope.updateState() { val jobs = List(100) { launch { repeat(1000) { counter + + } } } }

Slide 222

Slide 222 text

var mutext = Mutex() var counter = 0 suspend fun CoroutineScope.updateState() { 
 val jobs = List(100) { launch { repeat(1000) { mutext.lock() counter + + } } } }

Slide 223

Slide 223 text

var mutext = Mutex() var counter = 0 suspend fun CoroutineScope.updateState() { 
 val jobs = List(100) { launch { repeat(1000) { mutext.lock() try { counter + + } finally { mutext.unlock() } }

Slide 224

Slide 224 text

var mutext = Mutex() var counter = 0 suspend fun CoroutineScope.updateState() { List(100) { launch { repeat(1000) { mutext.lock() try { counter + + } finally { mutext.unlock() } }

Slide 225

Slide 225 text

fun Mutex.withLock(owner, action: () - > T): T { lock(owner) try { return action() } finally { unlock(owner) } }

Slide 226

Slide 226 text

var mutext = Mutex() var counter = 0 suspend fun CoroutineScope.updateState() { List(100) { launch { repeat(1000) { mutext.withLock { counter + + } 
 } } }

Slide 227

Slide 227 text

Actor

Slide 228

Slide 228 text

Actor

Slide 229

Slide 229 text

Actor State

Slide 230

Slide 230 text

Mailbox State Actor

Slide 231

Slide 231 text

Actor Mailbox Coroutine State

Slide 232

Slide 232 text

State Actor Mailbox Coroutine Event

Slide 233

Slide 233 text

State Actor Mailbox Coroutine Event

Slide 234

Slide 234 text

State Actor Mailbox Coroutine Event

Slide 235

Slide 235 text

sealed class CounterEvents { }

Slide 236

Slide 236 text

sealed class CounterEvents { object IncCounter : CounterEvents() }

Slide 237

Slide 237 text

sealed class CounterEvents { object IncCounter : CounterEvents() class GetCounter( val response: CompletableDeferred ): CounterEvents() }

Slide 238

Slide 238 text

fun CoroutineScope.counterActor() = actor { }

Slide 239

Slide 239 text

fun CoroutineScope.counterActor() = actor { var counter = 0 }

Slide 240

Slide 240 text

fun CoroutineScope.counterActor() = actor { var counter = 0 for (event in channel) { } }

Slide 241

Slide 241 text

fun CoroutineScope.counterActor() = actor { var counter = 0 for (event in channel) { when (event) { } } }

Slide 242

Slide 242 text

fun CoroutineScope.counterActor() = actor { var counter = 0 for (event in channel) { when (event) { is IncCounter - > counter + + } } }

Slide 243

Slide 243 text

fun CoroutineScope.counterActor() = actor { var counter = 0 for (event in channel) { when (event) { is IncCounter - > counter + + is GetCounter - > event.response.complete(counter) } } }

Slide 244

Slide 244 text

val actor = counterActor()

Slide 245

Slide 245 text

val actor = counterActor() suspend fun CoroutineScope.updateState() { List(100) { launch { repeat(1000) { actor.send(IncCounter()) 
 } } }

Slide 246

Slide 246 text

val actor = counterActor() val response = CompletableDeferred()

Slide 247

Slide 247 text

val actor = counterActor() val response = CompletableDeferred() actor.send(GetCounter(response))

Slide 248

Slide 248 text

val actor = counterActor() val response = CompletableDeferred() actor.send(GetCounter(response)) println(response.await())

Slide 249

Slide 249 text

Mutable State ● Mutex ● Actor

Slide 250

Slide 250 text

Resources ● Articles on testing flows, coroutine, context and more! 
 
 https: / / codingwithmohit.com/posts/ ● Talk on corotutines! 
 
 https: / / codingwithmohit.com/talks/

Slide 251

Slide 251 text

Thank You! www.codingwithmohit.com @heyitsmohit