Slide 1

Slide 1 text

Better Async with Kotlin Coroutines

Slide 2

Slide 2 text

@aditlal Adit Lal Product Engineer @vrushaliraut122 Vrushali Raut Product Engineer

Slide 3

Slide 3 text

Problem statement @WorkerThread fun loadWeather(city: String): List { … } @MainThread fun showWeather(weather: List) { … }

Slide 4

Slide 4 text

Thread { code } .start() object MyTask: AsyncTask() { override fun doInBackground { code } override fun onPostExecute { code } } Current Callbacks

Slide 5

Slide 5 text

Observable.from(dataSet) .map { code } .subscribe( { onNext }, { onError } ) Callbacks Current

Slide 6

Slide 6 text

Rx Solution weatherAPIService.getWeather(city="Bengaluru") .subscribeOn(io()) .observeOn(mainThread()) .subscribe ( { weatherResult -> showWeather(weatherResult) },{throwable-> handleError(throwable) })

Slide 7

Slide 7 text

What we need load { loadWeather(“Bengaluru”) } thenOnUI { showWeather(it) }

Slide 8

Slide 8 text

Corountines It can be thought of as an instance of suspend-able computation non-blocking code Coroutines simplify asynchronous programming by providing possibility to write code in direct style (sequentially).

Slide 9

Slide 9 text

“Truth can only be found in one place: the code”

Slide 10

Slide 10 text

Coroutine Example launch { println("CR start : ${getThreadName()}") Thread.sleep(100) println("CR ended : ${getThreadName()}") } run { println("Run start: ${getThreadName()}") Thread.sleep(300) println("Run ended: ${getThreadName()}") } fun funExperiment() { }

Slide 11

Slide 11 text

Run start: main CR start : commonPool-worker-1 Output Coroutine Example launch { println("CR start : ${getThreadName()}") Thread.sleep(100) println("CR ended : ${getThreadName()}") } run { println("Run start: ${getThreadName()}") Thread.sleep(300) println("Run ended: ${getThreadName()}") } fun funExperiment() { }

Slide 12

Slide 12 text

CR ended : commonPool-worker-1 Run ended: main Output Coroutine Example launch { println("CR start : ${getThreadName()}") Thread.sleep(100) println("CR ended : ${getThreadName()}") } run { println("Run start: ${getThreadName()}") Thread.sleep(300) println("Run ended: ${getThreadName()}") } } Run start: main CR start : commonPool-worker-1 fun funExperiment() {

Slide 13

Slide 13 text

Blocking Thread Time Function A Blocked Blocked Function B

Slide 14

Slide 14 text

Suspended fun Thread Time Function A Suspended Function B

Slide 15

Slide 15 text

Components Continuation Coroutine Builders Suspend functions Coroutine Context

Slide 16

Slide 16 text

Continuation Coroutine Builders Suspend functions Coroutine Context Components

Slide 17

Slide 17 text

interface Continuation { val context: CoroutineContext fun resume(value: T) fun resumeWithException(exception: Throwable) } Continuation Components

Slide 18

Slide 18 text

Components Continuation Coroutine Builders Suspend functions Coroutine Context

Slide 19

Slide 19 text

T withContext() Job launch() Deferred async() Returns result Uncaught exception - crash Fire and forget Uncaught exception - crash Non-Blocking future Uncaught exception - returned inside deferred Components

Slide 20

Slide 20 text

public actual fun launch( context: CoroutineContext = DefaultDispatcher, start: CoroutineStart = CoroutineStart.DEFAULT, parent: Job? = null, block: suspend CoroutineScope.() -> Unit ): Job Builders

Slide 21

Slide 21 text

public actual fun launch( context: CoroutineContext = DefaultDispatcher, start: CoroutineStart = CoroutineStart.DEFAULT, parent: Job? = null, block: suspend CoroutineScope.() -> Unit ): Job Builders

Slide 22

Slide 22 text

public actual fun launch( context: CoroutineContext = DefaultDispatcher, start: CoroutineStart = CoroutineStart.DEFAULT, parent: Job? = null, block: suspend CoroutineScope.() -> Unit ): Job Builders

Slide 23

Slide 23 text

public actual fun launch( context: CoroutineContext = DefaultDispatcher, start: CoroutineStart = CoroutineStart.DEFAULT, parent: Job? = null, block: suspend CoroutineScope.() -> Unit ): Job Builders

Slide 24

Slide 24 text

public actual fun launch( context: CoroutineContext = DefaultDispatcher, start: CoroutineStart = CoroutineStart.DEFAULT, parent: Job? = null, block: suspend CoroutineScope.() -> Unit ): Job Builders

Slide 25

Slide 25 text

public actual fun launch( context: CoroutineContext = DefaultDispatcher, start: CoroutineStart = CoroutineStart.DEFAULT, parent: Job? = null, block: suspend CoroutineScope.() -> Unit ): Job Builders

Slide 26

Slide 26 text

Components Continuation Coroutine Builders Suspend functions Coroutine Context

Slide 27

Slide 27 text

Suspend fun loadWeather(): Result fun loadWeather(listener: Continuation) suspend Transforms to

Slide 28

Slide 28 text

Components Continuation Coroutine Builders Suspend functions Coroutine Context

Slide 29

Slide 29 text

val uiContext: CoroutineContext = UI val bgContext: CoroutineContext = CommonPool Context

Slide 30

Slide 30 text

The plan 1. start coroutine 2. var apiData = fetchDataFromServer().await() 3. var result = parseData(apiData).await() 4. displayInList(data) 5. DSL

Slide 31

Slide 31 text

launch(context = bgContext) { val weatherResult = loadWeather("Bengaluru") } API

Slide 32

Slide 32 text

Coroutine context API launch(context = bgContext) { val weatherResult = loadWeather("Bengaluru") }

Slide 33

Slide 33 text

Coroutine builder launch(context = bgContext) { val weatherResult = loadWeather("Bengaluru") } Coroutine context API

Slide 34

Slide 34 text

val job = launch(context = CommonPool) { val weatherResult = loadWeather("Bengaluru") launch(context = UI) { showWeather(weatherResult) } } API and then show results

Slide 35

Slide 35 text

Another Coroutine API and then show results val job = launch(context = CommonPool) { val weatherResult = loadWeather("Bengaluru") launch(context = UI) { showWeather(weatherResult) } }

Slide 36

Slide 36 text

job.cancel() //cancels the execution of parent and child coroutines val job = launch(context = CommonPool) { val weatherResult = loadWeather("Bengaluru") launch(context = UI) { showWeather(weatherResult) } } API and then show results

Slide 37

Slide 37 text

• Simpler thread switching • Simple DSL • Dancing with final code Coroutines The Fun Solution

Slide 38

Slide 38 text

Solution fun getWeather(city="Bengaluru") { async(context = UI) { view.showLoading() val result = withContext(bgContext) { loadWeather(city) } showWeather(result) } }

Slide 39

Slide 39 text

Solution fun getWeather(city="Bengaluru") { launch(context = UI) { view.showLoading() val result = withContext(bgContext) { loadWeather(city) } showWeather(result) } }

Slide 40

Slide 40 text

Solution fun getWeather(city="Bengaluru") { launch(context = UI) { view.showLoading() val result = withContext(bgContext) { loadWeather(city) } showWeather(result) } }

Slide 41

Slide 41 text

Solution fun getWeather(city="Bengaluru") { launch(context = UI) { view.showLoading() val result = withContext(bgContext) { loadWeather(city) } showWeather(result) } }

Slide 42

Slide 42 text

suspend fun loadWeather (city="Bengaluru") { dataRepository.loadweather(city) } fun showWeather(weatherResult: List) { view.showWeather(weatherResult) } Solution

Slide 43

Slide 43 text

Where we were @WorkerThread fun loadWeather(city: String): List { … } @MainThread fun showWeather(weather: List) { … }

Slide 44

Slide 44 text

Solution fun getWeather(city="Bengaluru") { launch(context = UI) { view.showLoading() val result = withContext(bgContext) { loadWeather(city) } showWeather(result) } }

Slide 45

Slide 45 text

Fun DSL’s suspend fun load(block: () -> T): Deferred { } return block() fun Deferred.thenOnUI(uiFunction: (T) -> Unit) { } launch(UI) { uiFunction([email protected]()) }

Slide 46

Slide 46 text

Let’s Dance load { loadWeather(“Bengaluru”) } thenOnUI { showWeather(it) }

Slide 47

Slide 47 text

Handling exceptions

Slide 48

Slide 48 text

Stable

Slide 49

Slide 49 text

Resources try.kotlinlang.org kotlinresources.com github.com/Kotlin/kotlin-coroutines bit.ly/CodeLabCoroutines bit.ly/CoroutinesSourceDive bit.ly/CoroutinesAndroid

Slide 50

Slide 50 text

bit.ly/DevFest18Coroutines @aditlal Adit Lal @vrushaliraut122 Vrushali Raut Thats all folks!