Slide 1

Slide 1 text

Kotlin Coroutine Bruce Kim

Slide 2

Slide 2 text

Coroutine - Cheaper than thread [Explore01Thread] - a new way of managing background threads that can simplify code by reducing the need for callbacks. - Coroutines are a Kotlin feature that convert async callbacks for long-running tasks, such as database or network access, into sequential code.

Slide 3

Slide 3 text

- Parallel Stream Structure of [functional] sequential code is the same as parallel code - Coroutine Structure of [Imperative] synchronous code is the same as asynchronous code

Slide 4

Slide 4 text

Parallel vs Asynchronous - Where we are in JVM - Node was a huge paradigm shift. And it’s real power when it comes to scale - Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

Slide 5

Slide 5 text

Concurrency vs Non-blocking - Want to move on without waiting

Slide 6

Slide 6 text

Let’s examine parallel just a bit, in java - Parallel Stream [test1Stream] Structure of [functional] sequential code is the same as parallel code

Slide 7

Slide 7 text

Why not be happy with that? - Sequential code and parallel code structure was so different

Slide 8

Slide 8 text

Functional style is awesome - But, handling exceptions is a mess - Coroutines are asynchronous

Slide 9

Slide 9 text

From synchronous to asynchronous - [Explore02Launch] - launch

Slide 10

Slide 10 text

Blocking to non-blocking -16ms - 16ms * 60 frames = 960 ms O - 17ms * 60 frames = 1020ms X - 60 pages per second is ideal, as most people see this as high-quality, smooth motion.

Slide 11

Slide 11 text

Blocking to non-blocking -16ms Good Bad

Slide 12

Slide 12 text

How coroutines work? - Continuation [Explore03Continuation] - Traditional web server request vs human conversation

Slide 13

Slide 13 text

A sequential code [Explore04Http]

Slide 14

Slide 14 text

Using suspend While it's suspended waiting for a result, it unblocks the thread that it's running on so other functions or coroutines can run.

Slide 15

Slide 15 text

Doing asyn - [Explore05HttpAsync] - Deferred - Kotlin has a method Deferred.await() that is used to wait for the result from a coroutine started with the async builder.

Slide 16

Slide 16 text

CallbackToCoroutine [Explore06CallbackToCoroutine] - runBlocking

Slide 17

Slide 17 text

Reference - KotlinConf 2018 - Exploring Coroutines in Kotlin by Venkat Subramariam - How to Kotlin - from the Lead Kotlin Language Designer (Google I/O '18) - Android coroutine example - Converting existing callback APIs with coroutines - Testing coroutines Code: https://github.com/realwind2048/kotlinCoroutine