Slide 1

Slide 1 text

Structured Concurrency Asynchronous Shift in Kotlin @manuelvicnt Manuel Vicente Vivo

Slide 2

Slide 2 text

What problems are coroutines trying to solve?

Slide 3

Slide 3 text

Coroutines simplify async programming

Slide 4

Slide 4 text

Sync blocking fun loadData() { val data = networkRequest() show(data) } networkRequest show onDraw onDraw onDraw

Slide 5

Slide 5 text

Sync blocking fun networkRequest(): Data { // Blocking network request code }

Slide 6

Slide 6 text

fun loadData() { networkRequest { data -> show(data) } } Async with callbacks networkRequest show onDraw onDraw onDraw Network thread

Slide 7

Slide 7 text

fun networkRequest(onSuccess: (Data) -> Unit) { DefaultScheduler.execute { // Blocking network request code postToMainThread(onSuccess(result)) } } Async with callbacks

Slide 8

Slide 8 text

fun networkRequest(onSuccess: (Data) -> Unit) { DefaultScheduler.execute { // Blocking network request code postToMainThread(onSuccess(result)) } } Async with callbacks

Slide 9

Slide 9 text

fun networkRequest(onSuccess: (Data) -> Unit) { DefaultScheduler.execute { // Blocking network request code postToMainThread(onSuccess(result)) } } Async with callbacks

Slide 10

Slide 10 text

fun loadData() { networkRequest { data -> show(data) } } Async with callbacks

Slide 11

Slide 11 text

fun loadData() { networkRequest { data -> anotherRequest(data) { otherData -> // ... } } } Async with callbacks

Slide 12

Slide 12 text

fun loadData() { networkRequest { data -> anotherRequest(data) { otherData -> networkRequest { data -> anotherRequest(data) { otherData -> networkRequest { data -> anotherRequest(data) { otherData -> networkRequest { data -> anotherRequest(data) { otherData -> networkRequest { data -> anotherRequest(data) { otherData -> networkRequest { data -> anotherRequest(data) { otherData -> networkRequest { data -> anotherRequest(data) { otherData -> networkRequest { data -> anotherRequest(data) { otherData -> networkRequest { data -> anotherRequest(data) { otherData -> networkRequest { data -> anotherRequest(data) { otherData -> // Hey there! You want more? } } } } } Callback Hell fun loadData() { networkRequest { data -> anotherRequest(data) { otherData ->

Slide 13

Slide 13 text

Best of both worlds?

Slide 14

Slide 14 text

suspend fun loadData() { val data = networkRequest() show(data) } Async with coroutines onDraw onDraw onDraw Network thread networkRequest show

Slide 15

Slide 15 text

suspend fun loadData() { val data = networkRequest() show(data) }

Slide 16

Slide 16 text

suspend fun loadData() { val data = networkRequest() show(data) } suspend

Slide 17

Slide 17 text

suspend fun loadData() { val data = networkRequest() show(data) } suspend resume

Slide 18

Slide 18 text

suspend fun loadData() { val data = networkRequest() show(data) } suspend Callback resume

Slide 19

Slide 19 text

Callbacks? The Kotlin compiler writes them under the hood when the computation can suspend

Slide 20

Slide 20 text

Continuation Coroutines call those “callbacks” Continuation

Slide 21

Slide 21 text

Continuation suspend fun loadData() { val data = networkRequest() show(data) }

Slide 22

Slide 22 text

Continuation fun loadData(continuation: Continuation) { val data = networkRequest(continuation) show(data) }

Slide 23

Slide 23 text

State Machine Continuations form a state machine

Slide 24

Slide 24 text

State Machine LoadData Network Request State 0 - init

Slide 25

Slide 25 text

State Machine LoadData Network Request State 1 suspend

Slide 26

Slide 26 text

State Machine LoadData Network Request State 2 resume

Slide 27

Slide 27 text

State Machine LoadData Network Request State 3 - exit

Slide 28

Slide 28 text

Continuation-Passing Style (CPS) Disclaimer Not Covered

Slide 29

Slide 29 text

With Coroutines… Computation gets suspended without blocking the thread

Slide 30

Slide 30 text

suspend fun loadData() { val data = networkRequest() show(data) }

Slide 31

Slide 31 text

suspend fun loadData() { val data = networkRequest() show(data) } suspend fun networkRequest(): Data

Slide 32

Slide 32 text

suspend fun loadData() { val data = networkRequest() show(data) } suspend fun networkRequest(): Data = withContext(Dispatchers.IO) { }

Slide 33

Slide 33 text

suspend fun loadData() { val data = networkRequest() show(data) } suspend fun networkRequest(): Data = withContext(Dispatchers.IO) { // Blocking network request code } Dispatchers.IO

Slide 34

Slide 34 text

.Default .Main Dispatchers .IO

Slide 35

Slide 35 text

Dispatchers .IO .Main .Default

Slide 36

Slide 36 text

.IO .Main .Default Network & Disk

Slide 37

Slide 37 text

.IO .Main .Default Network & Disk CPU

Slide 38

Slide 38 text

.IO .Main .Default Network & Disk UI/Non-blocking CPU

Slide 39

Slide 39 text

suspend fun loadData() { val data = networkRequest() show(data) } suspend fun networkRequest(): Data = withContext(Dispatchers.IO) { // Blocking network request code }

Slide 40

Slide 40 text

suspend fun loadData() { val data = networkRequest() show(data) } suspend fun networkRequest(): Data = withContext(Dispatchers.IO) { // Blocking network request code } Main Safe

Slide 41

Slide 41 text

But… what is a coroutine?

Slide 42

Slide 42 text

Coroutine Runnable with super powers Takes a block of code to run in a thread

Slide 43

Slide 43 text

Asynchronicity expressed as sequential code that is easy to read and reason about Other perks: exception handling and cancellation ❤ Coroutine

Slide 44

Slide 44 text

suspend fun loadData() { val data = networkRequest() show(data) }

Slide 45

Slide 45 text

suspend fun loadData() { val data = networkRequest() show(data) } fun onButtonClicked() { loadData() } Suspend fun ‘loadData’ must be called from a coroutine

Slide 46

Slide 46 text

suspend fun loadData() { val data = networkRequest() show(data) } fun onButtonClicked() { launch { loadData() } }

Slide 47

Slide 47 text

suspend fun loadData() { val data = networkRequest() show(data) } fun onButtonClicked() { launch { loadData() } } Who can cancel this execution? Does it follow a particular lifecycle? Who gets exceptions if it fails?

Slide 48

Slide 48 text

Structured Concurrency

Slide 49

Slide 49 text

Scopes Keep track of coroutines Ability to cancel them Gets exceptions

Slide 50

Slide 50 text

fun onButtonClicked() { launch { loadData() } } Launch must be called in a scope // MyViewModel.kt

Slide 51

Slide 51 text

fun onButtonClicked() { launch { loadData() } } // MyViewModel.kt

Slide 52

Slide 52 text

val scope = CoroutineScope(Dispatchers.Main) fun onButtonClicked() { launch { loadData() } } // MyViewModel.kt

Slide 53

Slide 53 text

val scope = CoroutineScope(Dispatchers.Main) fun onButtonClicked() { scope.launch { loadData() } } // MyViewModel.kt

Slide 54

Slide 54 text

val scope = CoroutineScope(Dispatchers.Main) fun onButtonClicked() { scope.launch { loadData() } } When loadData throws, the scope gets the exception

Slide 55

Slide 55 text

val scope = CoroutineScope(Dispatchers.Main) Parent fun onButtonClicked() { scope.launch { loadData() } }

Slide 56

Slide 56 text

val scope = CoroutineScope(Dispatchers.Main) Parent Child fun onButtonClicked() { scope.launch { loadData() } }

Slide 57

Slide 57 text

fun onButtonClicked() { scope.launch { loadData() } } Child fun onCleared() { scope.cancel() }

Slide 58

Slide 58 text

Cancelling a Scope Cancels all children coroutines Useless, cannot start more coroutines

Slide 59

Slide 59 text

suspend fun loadData() { val data = networkRequest() show(data) }

Slide 60

Slide 60 text

suspend fun loadData() { val data = networkRequest() show(data) } Runs in a scope

Slide 61

Slide 61 text

When a function returns, it has completed all work

Slide 62

Slide 62 text

When a function returns, it has completed all work suspend

Slide 63

Slide 63 text

suspend fun loadData() { val data = networkRequest() show(data) }

Slide 64

Slide 64 text

Scopes Exception Handling

Slide 65

Slide 65 text

fun onButtonClicked() { scope.launch { loadData() } } val scope = CoroutineScope(Dispatchers.Main) // MyViewModel.kt

Slide 66

Slide 66 text

fun onButtonClicked() { scope.launch { loadData() } } val scope = CoroutineScope( Dispatchers.Main + Job() ) // MyViewModel.kt

Slide 67

Slide 67 text

Scope with a Job When a child fails, it propagates cancellation to other (scope) children When a failure is notified, the scope propagates the exception up

Slide 68

Slide 68 text

fun onButtonClicked() { scope.launch { loadData() } } val scope = CoroutineScope( Dispatchers.Main + Job() ) // MyViewModel.kt

Slide 69

Slide 69 text

fun onButtonClicked() { scope.launch { loadData() } } val scope = CoroutineScope( Dispatchers.Main + SupervisorJob() ) // MyViewModel.kt

Slide 70

Slide 70 text

Scope with a SupervisorJob The failure of a child doesn’t affect other (scope) children When a failure is notified, the scope doesn’t do anything

Slide 71

Slide 71 text

fun onButtonClicked() { scope.launch { loadData() } } val scope = CoroutineScope( Dispatchers.Main + SupervisorJob() ) // MyViewModel.kt

Slide 72

Slide 72 text

TL;DR; work is completed suspend fun returns

Slide 73

Slide 73 text

TL;DR; work is completed suspend fun returns scope cancelled children cancel

Slide 74

Slide 74 text

TL;DR; work is completed suspend fun returns scope cancelled children cancel coroutine errors scope notified

Slide 75

Slide 75 text

Create Coroutines

Slide 76

Slide 76 text

Launch Async v s

Slide 77

Slide 77 text

Launch Async

Slide 78

Slide 78 text

Creates a new Coroutine Creates a new Coroutine Launch Async

Slide 79

Slide 79 text

Launch Creates a new Coroutine Fire and Forget scope.launch(Dispatchers.IO) { loggingService.upload(logs) }

Slide 80

Slide 80 text

Async Creates a new Coroutine Returns a value suspend fun getUser(userId: String): User = coroutineScope { val deferred = async(Dispatchers.IO) { userService.getUser(userId) } deferred.await() }

Slide 81

Slide 81 text

Async Creates a new Coroutine Returns a value suspend fun getUser(userId: String): User = coroutineScope { val deferred = async(Dispatchers.IO) { userService.getUser(userId) } deferred.await() }

Slide 82

Slide 82 text

Async Creates a new Coroutine Returns a value suspend fun getUser(userId: String): User = coroutineScope { val deferred = async(Dispatchers.IO) { userService.getUser(userId) } deferred.await() }

Slide 83

Slide 83 text

Async Creates a new Coroutine Returns a value suspend fun getUser(userId: String): User = coroutineScope { val deferred = async(Dispatchers.IO) { userService.getUser(userId) } deferred.await() }

Slide 84

Slide 84 text

Async Creates a new Coroutine Returns a value suspend fun getUser(userId: String): User = coroutineScope { val deferred = async(Dispatchers.IO) { userService.getUser(userId) } deferred.await() }

Slide 85

Slide 85 text

Async Creates a new Coroutine Returns a value suspend fun getUser(userId: String): User = coroutineScope { val deferred = async(Dispatchers.IO) { userService.getUser(userId) } deferred.await() }

Slide 86

Slide 86 text

Creates a new Coroutine Creates a new Coroutine Fire and Forget Returns a value Launch Async

Slide 87

Slide 87 text

Creates a new Coroutine Creates a new Coroutine Takes a Dispatcher Takes a Dispatcher Fire and Forget Returns a value Launch Async

Slide 88

Slide 88 text

Creates a new Coroutine Creates a new Coroutine Takes a Dispatcher Takes a Dispatcher Executed in a Scope Executed in a Scope Fire and Forget Returns a value Launch Async

Slide 89

Slide 89 text

Creates a new Coroutine Creates a new Coroutine Takes a Dispatcher Takes a Dispatcher Executed in a Scope Executed in a Scope Not a suspend function Not a suspend function Fire and Forget Returns a value Launch Async

Slide 90

Slide 90 text

Creates a new Coroutine Creates a new Coroutine Takes a Dispatcher Takes a Dispatcher Executed in a Scope Executed in a Scope Re-throws exceptions Not a suspend function Not a suspend function Fire and Forget Returns a value Launch Async

Slide 91

Slide 91 text

Creates a new Coroutine Creates a new Coroutine Takes a Dispatcher Takes a Dispatcher Executed in a Scope Executed in a Scope Not a suspend function Not a suspend function Holds on exceptions until await is called Fire and Forget Returns a value Launch Async Re-throws exceptions

Slide 92

Slide 92 text

Exception handling

Slide 93

Slide 93 text

Wrapping in a try-catch block scope.launch(Dispatchers.Default) { try { loggingService.upload(logs) } catch(e: Exception) { // Handle Exception } }

Slide 94

Slide 94 text

suspend fun getUser(userId: String): User { coroutineScope { val deferred = async(Dispatchers.IO) { userService.getUser(userId) } try { deferred.await() } catch(e: Exception) { // Handle exception } } }

Slide 95

Slide 95 text

suspend fun getUser(userId: String): User { coroutineScope { val deferred = async(Dispatchers.IO) { userService.getUser(userId) } try { deferred.await() } catch(e: Exception) { // Handle exception } } }

Slide 96

Slide 96 text

suspend fun getUser(userId: String): User { coroutineScope { val deferred = async(Dispatchers.IO) { userService.getUser(userId) } try { deferred.await() } catch(e: Exception) { // Handle exception } } }

Slide 97

Slide 97 text

scope.launch(Dispatchers.IO) { for (name in files) { readFile(name) } }

Slide 98

Slide 98 text

Cancellation requires co-operation

Slide 99

Slide 99 text

scope.launch(Dispatchers.IO) { for (name in files) { readFile(name) } }

Slide 100

Slide 100 text

Check if the coroutine is Active scope.launch(Dispatchers.IO) { for (name in files) { if (!isActive) break readFile(name) } }

Slide 101

Slide 101 text

When to mark a function as suspend

Slide 102

Slide 102 text

suspend fun loadData() { val data = networkRequest() show(data) } When it calls other suspend functions

Slide 103

Slide 103 text

suspend fun loadData() { val data = networkRequest() show(data) } When it calls other suspend functions

Slide 104

Slide 104 text

When NOT to mark a function as suspend

Slide 105

Slide 105 text

When it doesn’t call suspend functions fun onButtonClicked() { scope.launch { loadData() } }

Slide 106

Slide 106 text

Tip Don’t mark a function suspend unless you’re forced to

Slide 107

Slide 107 text

Unit Testing Coroutines

Slide 108

Slide 108 text

Use Case 1 The test doesn’t trigger new coroutines

Slide 109

Slide 109 text

suspend fun loadData() { val data = networkRequest() show(data) } // MyViewModel.kt

Slide 110

Slide 110 text

@Test fun `Test loadData happy path`() = runBlocking { val viewModel = MyViewModel() viewModel.loadData() // Assert show did something } // MyViewModelTest.kt

Slide 111

Slide 111 text

Use Case 2 The test triggers new coroutines

Slide 112

Slide 112 text

class MyViewModel { val scope = CoroutineScope( Dispatchers.Main + SupervisorJob() ) fun onButtonClicked() { scope.launch { loadData() } } }

Slide 113

Slide 113 text

class MyViewModel { val scope = CoroutineScope( Dispatchers.Main + SupervisorJob() ) fun onButtonClicked() { scope.launch { loadData() } } }

Slide 114

Slide 114 text

@Test fun `Test loadData happy path`() = runBlocking { val viewModel = MyViewModel() viewModel.onButtonClicked() // Assert show did something } // MyViewModelTest.kt

Slide 115

Slide 115 text

@Test fun `Test loadData happy path`() = runBlocking { val viewModel = MyViewModel() viewModel.onButtonClicked() // Assert show did something } // MyViewModelTest.kt

Slide 116

Slide 116 text

@Test fun `Test loadData happy path`() { val viewModel = MyViewModel() viewModel.onButtonClicked() // Wait for the result -> using a CountDownLatch // LiveDataTestUtil, Mockito await, etc. } // MyViewModelTest.kt

Slide 117

Slide 117 text

@Test fun `Test loadData happy path`() { val viewModel = MyViewModel() viewModel.onButtonClicked() // Wait for the result -> using a CountDownLatch // LiveDataTestUtil, Mockito await, etc. } // MyViewModelTest.kt Code Smell!! Bad practice

Slide 118

Slide 118 text

class MyViewModel { val scope = CoroutineScope( Dispatchers.Main + SupervisorJob() ) fun onButtonClicked() { scope.launch { loadData() } } }

Slide 119

Slide 119 text

class MyViewModel( private val dispatcher: CoroutineDispatcher ) { val scope = CoroutineScope( Dispatchers.Main + SupervisorJob() ) fun onButtonClicked() { scope.launch(dispatcher) { loadData() } } }

Slide 120

Slide 120 text

class MyViewModel( private val dispatcher: CoroutineDispatcher ) { val scope = CoroutineScope( Dispatchers.Main + SupervisorJob() ) fun onButtonClicked() { scope.launch(dispatcher) { loadData() } } }

Slide 121

Slide 121 text

val testDispatcher = TestCoroutineDispatcher() @Test fun `Test loadData happy path`() = testDispatcher.runBlockingTest { val viewModel = MyViewModel(testDispatcher) viewModel.onButtonClicked() // Assert show did something } // MyViewModelTest.kt

Slide 122

Slide 122 text

val testDispatcher = TestCoroutineDispatcher() @Test fun `Test loadData happy path`() = testDispatcher.runBlockingTest { val viewModel = MyViewModel(testDispatcher) viewModel.onButtonClicked() // Assert show did something } // MyViewModelTest.kt

Slide 123

Slide 123 text

val testDispatcher = TestCoroutineDispatcher() @Test fun `Test loadData happy path`() = testDispatcher.runBlockingTest { val viewModel = MyViewModel(testDispatcher) viewModel.onButtonClicked() // Assert show did something } // MyViewModelTest.kt

Slide 124

Slide 124 text

class MyViewModel( private val dispatcher: CoroutineDispatcher ) { val scope = CoroutineScope( Dispatchers.Main + SupervisorJob() ) fun onButtonClicked() { // Do something else scope.launch(dispatcher) { loadData() } } }

Slide 125

Slide 125 text

val testDispatcher = TestCoroutineDispatcher() @Test fun `Test loadData happy path`() = testDispatcher.runBlockingTest { val viewModel = MyViewModel(testDispatcher) testDispatcher.pauseDispatcher() viewModel.onButtonClicked() // Assert onButtonClicked did something else } // MyViewModelTest.kt

Slide 126

Slide 126 text

val testDispatcher = TestCoroutineDispatcher() @Test fun `Test loadData happy path`() = testDispatcher.runBlockingTest { val viewModel = MyViewModel(testDispatcher) testDispatcher.pauseDispatcher() viewModel.onButtonClicked() // Assert onButtonClicked did something else testDispatcher.resumeDispatcher() // Assert show did something } // MyViewModelTest.kt

Slide 127

Slide 127 text

Testing Use runBlocking when the test doesn’t create new coroutines

Slide 128

Slide 128 text

Testing As a good practice, inject Dispatchers and use TestCoroutineDispatcher in tests

Slide 129

Slide 129 text

What we covered What problems Coroutines solve Dispatchers & withContext What a Coroutine is How coroutines work under the hood Principles of Structured Concurrency How to create Coroutines Exception Handling When to mark a function as suspend Testing Coroutines & TestCoroutineDispatcher

Slide 130

Slide 130 text

Thank You Questions? @manuelvicnt Manuel Vicente Vivo