Slide 1

Slide 1 text

BETTER ASYNC ON ANDROID WITH KOTLIN COROUTINES Erik Hellman - @ErikHellman https://speakerdeck.com/erikhellman/better-async-with-kotlin-coroutines

Slide 2

Slide 2 text

–Developers “Async is hard.”

Slide 3

Slide 3 text

We all suck at multi tasking!

Slide 4

Slide 4 text

// This must run on a background thread @WorkerThread fun loadTweets(query: String): List { // Load tweets matching the search query } // This must run on the main thread @MainThread fun showTweets(tweets: List) { // Display tweets }

Slide 5

Slide 5 text

inner class LoadTweetAsyncTask : AsyncTask>() { override fun doInBackground(vararg params: String): List { return loadTweets(params[0]) } override fun onPostExecute(result: List?) { showTweets(result) } }

Slide 6

Slide 6 text

val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_ .subscribe { tweets ->_ showTweets(tweets)_ }_ _ disposable.dispose()_

Slide 7

Slide 7 text

val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_ .subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_

Slide 8

Slide 8 text

val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_ .subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_

Slide 9

Slide 9 text

val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_ .subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_

Slide 10

Slide 10 text

val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_ .subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_

Slide 11

Slide 11 text

val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_ .subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_

Slide 12

Slide 12 text

WHAT WE WANT val tweets = loadTweets(”#AndroidMakers”) showTweets(tweets)

Slide 13

Slide 13 text

WHAT WE CAN HAVE load { loadTweets(“#AndroidMakers”) } then { showTweets(it) } STAY TUNED!

Slide 14

Slide 14 text

Coroutines = State Machine + Queue

Slide 15

Slide 15 text

WAT?

Slide 16

Slide 16 text

LET’S TRY A DIFFERENT ANALOGY!

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Restore state from savedInstanceState } override fun onSaveInstanceState(outState: Bundle?) { super.onSaveInstanceState(outState) // Save the state of your app } }

Slide 19

Slide 19 text

Activity Bundle The “process” of the user The state of the process

Slide 20

Slide 20 text

Activity Bundle Coroutine Continuation

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

BUT WHAT IS A COROUTINE, REALLY?

Slide 23

Slide 23 text

–Donald Knuth “Subroutines are special cases of ... coroutines.”

Slide 24

Slide 24 text

Pause d'eau…

Slide 25

Slide 25 text

launch {. val tweets = loadTweets("#AndroidMakers") }.

Slide 26

Slide 26 text

launch(context = CommonPool) {. val tweets = loadTweets("#AndroidMakers") }. CoroutineContext - How to run this coroutine, including which thread

Slide 27

Slide 27 text

override fun onCreate(savedInstanceState: Bundle?) {. super.onCreate(savedInstanceState). setContentView(R.layout.activity_main). launch(context = CommonPool) {. val tweets = loadTweets("#AndroidMakers"). }. }.

Slide 28

Slide 28 text

val job = launch(context = CommonPool) {. val tweets = loadTweets("#AndroidMakers"). }. job.cancel().

Slide 29

Slide 29 text

val job = launch(context = CommonPool) {. val tweets = loadTweets("#AndroidMakers"). launch(context = UI) {. showTweets(tweets). }. }. . job.cancel(). Cancelled with parent! Switch context (and thread)

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

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

Slide 35

Slide 35 text

val deferred = async(context = CommonPool) {. loadTweets("#AndroidMakers"). }. launch(context = UI) {. showTweets(deferred.await()). }. deferred.cancel(). Will throw CancellationException!

Slide 36

Slide 36 text

// Launch a coroutine that returns a deferred value val deferred: Deferred> = async { loadTweets("#AndroidMakers") } // Fire and forget! val job: Job = launch { loadTweets("#AndroidMakers") }

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

SUSPENDED FUNCTION suspend fun CompletableFuture.await(): T = suspendCoroutine { cont: Continuation -> whenComplete { result, exception -> if (exception == null) // the future has been completed normally cont.resume(result) else // the future has completed with an exception cont.resumeWithException(exception) } }

Slide 39

Slide 39 text

Pause d'eau…

Slide 40

Slide 40 text

LET’S MAKE A DSL*! * Domain Specific Language

Slide 41

Slide 41 text

fun Activity.load(loadFunction: () -> T) {. // TODO perform background loading here. }.

Slide 42

Slide 42 text

fun Activity.load(loadFunction: () -> T): T {. return loadFunction(). }.

Slide 43

Slide 43 text

fun Activity.load(loadFunction: () -> T): Deferred {. return async { loadFunction() }. }.

Slide 44

Slide 44 text

fun Activity.load(loadFunction: () -> T): Deferred {. return async { loadFunction() }. }. . fun Deferred.then(uiFunction: (T) -> Unit) {. launch(UI) { uiFunction([email protected]()) }. }.

Slide 45

Slide 45 text

fun Activity.load(loadFunction: () -> T): Deferred {. return async { loadFunction() }. }. . infix fun Deferred.then(uiFunction: (T) -> Unit) {. launch(UI) { uiFunction([email protected]()) }. }.

Slide 46

Slide 46 text

override fun onStart() { super.onStart() load { loadTweets("#AndroidMakers") } then { showTweets(it) } } ALMOST THERE!

Slide 47

Slide 47 text

LIFECYCLE OBSERVER class CoroutineLifecycleListener : LifecycleObserver {. @OnLifecycleEvent(Lifecycle.Event.ON_STOP). fun onStop() {. // Called at onStop() }. }.

Slide 48

Slide 48 text

LIFECYCLE OBSERVER class CoroutineLifecycleListener(val job: Job) : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { if(!job.isCancelled) job.cancel() } }

Slide 49

Slide 49 text

fun Activity.load(loadFunction: () -> T): Deferred {. return asynco{oloadFunction()o}o }. . infix fun Deferred.then(uiFunction: (T) -> Unit) {. launch(context = UI) {. uiFunction([email protected]()). }. }.

Slide 50

Slide 50 text

fun LifecycleOwner.load(loadFunction: () -> T): Deferred {. val deferred = asynco{oloadFunction()o}o lifecycle.addObserver(CoroutineLifecycleListener(deferred)). return deferred. }. . infix fun Deferred.then(uiFunction: (T) -> Unit) {. launch(context = UI) {. uiFunction([email protected]()). }. }.

Slide 51

Slide 51 text

val loaderContext: CoroutineContext = newFixedThreadPoolContext(2, "loader") fun LifecycleOwner.load(context: CoroutineContext = loaderContext, loadFunction: () -> T): Deferred { val deferred = async(context = context, start = CoroutineStart.LAZY) { loadFunction() } lifecycle.addObserver(CoroutineLifecycleListener(deferred)) return deferred } infix fun Deferred.then(uiFunction: (T) -> Unit) { launch(context = UI) { uiFunction([email protected]()) } } MORE CONTROL

Slide 52

Slide 52 text

val loaderContext: CoroutineContext = newFixedThreadPoolContext(2, "loader") fun LifecycleOwner.load(context: CoroutineContext = loaderContext, loadFunction: () -> T): Deferred { val deferred = async(context = context, start = CoroutineStart.LAZY) { loadFunction() } lifecycle.addObserver(CoroutineLifecycleListener(deferred)) return deferred } infix fun Deferred.then(uiFunction: (T) -> Unit) { launch(context = UI) { uiFunction([email protected]()) } } MORE CONTROL

Slide 53

Slide 53 text

val loaderContext: CoroutineContext = newFixedThreadPoolContext(2, "loader") fun LifecycleOwner.load(context: CoroutineContext = loaderContext, loadFunction: () -> T): Deferred { val deferred = async(context = context, start = CoroutineStart.LAZY) { loadFunction() } lifecycle.addObserver(CoroutineLifecycleListener(deferred)) return deferred } infix fun Deferred.then(uiFunction: (T) -> Unit) { launch(context = UI) { uiFunction([email protected]()) } } MORE CONTROL

Slide 54

Slide 54 text

override fun onStart() { super.onStart() load { loadTweets("#AndroidMakers") } then { showTweets(it) } } DONE!

Slide 55

Slide 55 text

WHAT ABOUT ERRORS?

Slide 56

Slide 56 text

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

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

override fun onStart() {. super.onStart(). . load.{. loadTweets("#AndroidMakers"). }.then {. showTweets(it). }. }.

Slide 59

Slide 59 text

override fun onStart() {. super.onStart(). . load.{. loadTweets("#AndroidMakers"). }.then {. try {. showTweets(it). } catch (e: Exception) {. showErrorMessage(e). }. }. }.

Slide 60

Slide 60 text

BUT WAIT! THERE IS MORE!

Slide 61

Slide 61 text

// Create a channel for reading and writing numbers val channel = Channel() // Send 10 integers to the channel on a background thread launch(CommonPool) { for (x in 1..10) channel.send(x) } // Read the numbers from the channel launch(UI) { for (number in channel) println(number) } CHANNELS!

Slide 62

Slide 62 text

CAN BE USED LIKE A SEQUENCE! launch(UI) { channel.filter { it % 2 == 0 } .map(CommonPool) { it * 2 } .consumeEach { updateUI(it) } } Operators can take a coroutine context!

Slide 63

Slide 63 text

CAN HAVE MULTIPLE CONSUMERS val clickChannel = Channel() button.setOnClickListener { view -> launch { clickChannel.send(view) } } repeat(10)_{_ launch(CommonPool)_{_ clickChannel.consumeEach_{_ val result = doHeavyWork()_ }_ }_ }_

Slide 64

Slide 64 text

…OR MULTIPLE PRODUCERS val resultChannel = Channel()_ _ repeat(10)_{_ launch(CommonPool)_{_ clickChannel.consumeEach_{_ val_result_=_doHeavyWork()_ resultChannel.send(result)_ }_ }_ }_ _ launch(UI)_{ resultChannel.consumeEach { updateUI(it) } }

Slide 65

Slide 65 text

button.setOnClickListener { load { loadTweets(“#AndroidMakers") } then { showTweets(it) } } How can I throttle the click callbacks? Launches a new coroutine on every click!

Slide 66

Slide 66 text

ACTORS

Slide 67

Slide 67 text

val clickActor = actor(UI) { channel.map(CommonPool) { loadTweets("#AndroidMakers") } .consumeEach { showTweets(it) } } button.setOnClickListener { clickActor.offer(it) } ... clickActor.close() Drop this event if the receiver is busy!

Slide 68

Slide 68 text

CONFUSED?

Slide 69

Slide 69 text

LET’S EXTEND OUR DSL!

Slide 70

Slide 70 text

class LoadingChannel(val lifecycle: Lifecycle,_ val view: View,_ val loadFunction: () -> T) {_ _ }_

Slide 71

Slide 71 text

class LoadingChannel(val lifecycle: Lifecycle,_ val view: View,_ val loadFunction: () -> T) {_ infix fun then(uiFunction: (T) -> Unit) {_ val job = Job() val actor = actor(context = UI, parent = job) { }_ _ lifecycle.addObserver(CoroutineLifecycleListener(job))_ _ view.setOnClickListener { actor.offer(Unit) }_ }_ }_

Slide 72

Slide 72 text

class LoadingChannel(val lifecycle: Lifecycle,_ val view: View,_ val loadFunction: () -> T) {_ infix fun then(uiFunction: (T) -> Unit) {_ val job = Job() val actor = actor(context = UI, parent = job) { channel.map(CommonPool) { loadFunction() }_ .consumeEach { uiFunction(it) }_ }_ _ lifecycle.addObserver(CoroutineLifecycleListener(job))_ _ view.setOnClickListener { actor.offer(Unit) }_ }_ }_

Slide 73

Slide 73 text

class LoadingChannel(val lifecycle: Lifecycle,_ val view: View,_ val loadFunction: () -> T) {_ infix fun then(uiFunction: (T) -> Unit) {_ val job = Job() val actor = actor(context = UI, parent = job) { channel.map(CommonPool) { loadFunction() }_ .consumeEach { uiFunction(it) }_ }_ _ lifecycle.addObserver(ActorLifecycleListener(job))_ _ view.setOnClickListener { actor.offer(Unit) }_ }_ }_

Slide 74

Slide 74 text

fun LifecycleOwner.whenClicking(view: View, loadFunction: () -> T) : LoadingChannel { return LoadingChannel(lifecycle, view, loadFunction) }

Slide 75

Slide 75 text

override fun onCreate(savedInstanceState: Bundle?) {_ super.onCreate(savedInstanceState)_ setContentView(R.layout.activity_main)_ _ whenClicking(button) {_ loadTweets("#AndroidMakers")_ }_ }_

Slide 76

Slide 76 text

override fun onCreate(savedInstanceState: Bundle?) {_ super.onCreate(savedInstanceState)_ setContentView(R.layout.activity_main)_ _ whenClicking(button) {_ loadTweets("#AndroidMakers")_ }_then {_ showTweets(it)_ }_ }_

Slide 77

Slide 77 text

DOES THIS REPLACE RXJAVA? NO!

Slide 78

Slide 78 text

COROUTINE LIBRARIES

Slide 79

Slide 79 text

RETROFIT ADAPTER https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter val retrofit = Retrofit.Builder() .baseUrl("https://example.com/") .addCallAdapterFactory(CoroutineCallAdapterFactory()) .build() interface MyService { @GET("/user") fun getUser(): Deferred // or @GET("/user") fun getUser(): Deferred> }

Slide 80

Slide 80 text

GRADLE STUFF kotlin { experimental { coroutines "enable" } } dependencies { implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:0.22.5" implementation “org.jetbrains.kotlinx:kotlinx-coroutines-android:0.22.5" }

Slide 81

Slide 81 text

RESOURCES • https://github.com/Kotlin/kotlinx.coroutines/ • https://github.com/Kotlin/kotlinx.coroutines/blob/master/coroutines-guide.md • https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/coroutines-guide-ui.md • https://github.com/JakeWharton/retrofit2-kotlin-coroutines-adapter • https://hellsoft.se/simple-asynchronous-loading-with-kotlin-coroutines-f26408f97f46 • https://github.com/ErikHellman/KotlinAsyncWithCoroutines

Slide 82

Slide 82 text

THANK YOU FOR LISTENING! https://speakerdeck.com/erikhellman/better-async-with-kotlin-coroutines