Share
Embed
Better Async With Kotlin Coroutines
Android application development is inherently asynchronous. Even the simplest Android application requires the developer to track asynchronous callbacks of the activity, often leading to the infamous callback hell. In this talk, we will have a look at the latest addition to the solutions for dealing with asynchronous programming on Android; Kotlin Coroutines. We'll learn about what coroutines are, how they differ from other models and how to use it with Kotlin on Android.
Erik Hellman
April 20, 2018
Transcript
82 slides
-
BETTER ASYNC ON ANDROID WITH KOTLIN COROUTINES Erik Hellman -
@ErikHellman https://speakerdeck.com/erikhellman/better-async-with-kotlin-coroutines -
// This must run on a background thread @WorkerThread fun
loadTweets(query: String): List<Tweet> { // Load tweets matching the search query } // This must run on the main thread @MainThread fun showTweets(tweets: List<Tweet>) { // Display tweets } -
inner class LoadTweetAsyncTask : AsyncTask<String, Unit, List<Tweet>>() { override fun
doInBackground(vararg params: String): List<Tweet> { return loadTweets(params[0]) } override fun onPostExecute(result: List<Tweet>?) { showTweets(result) } } -
val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_
.subscribe { tweets ->_ showTweets(tweets)_ }_ _ disposable.dispose()_ -
val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_
.subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_ -
val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_
.subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_ -
val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_
.subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_ -
val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_
.subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_ -
val disposable = Single_ .fromCallable { loadTweets("#AndroidMakers") }_ .subscribeOn(Schedulers.io())_ .observeOn(AndroidSchedulers.mainThread())_
.subscribe(_ {_tweets -> showTweets(tweets)_}_ {_error -> showError(error)_})_ _ disposable.dispose()_ -
WHAT WE CAN HAVE load { loadTweets(“#AndroidMakers”) } then {
showTweets(it) } STAY TUNED! -
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 } } -
CONTINUATION? interface Continuation<in T> { val context: CoroutineContext fun resume(value:
T) fun resumeWithException(exception: Throwable) } -
launch(context = CommonPool) {. val tweets = loadTweets("#AndroidMakers") }. CoroutineContext
- How to run this coroutine, including which thread -
override fun onCreate(savedInstanceState: Bundle?) {. super.onCreate(savedInstanceState). setContentView(R.layout.activity_main). launch(context = CommonPool)
{. val tweets = loadTweets("#AndroidMakers"). }. }. -
val job = launch(context = CommonPool) {. val tweets =
loadTweets("#AndroidMakers"). }. job.cancel(). -
val job = launch(context = CommonPool) {. val tweets =
loadTweets("#AndroidMakers"). launch(context = UI) {. showTweets(tweets). }. }. . job.cancel(). Cancelled with parent! Switch context (and thread) -
public actual fun launch(. context: CoroutineContext = DefaultDispatcher,. start: CoroutineStart
= CoroutineStart.DEFAULT,. parent: Job? = null,. block: suspend CoroutineScope.() -> Unit. ): Job. -
public actual fun launch( context: CoroutineContext = DefaultDispatcher,. start: CoroutineStart
= CoroutineStart.DEFAULT, parent: Job? = null, block: suspend CoroutineScope.() -> Unit ): Job WHAT THREAD TO RUN ON -
public actual fun launch( context: CoroutineContext = DefaultDispatcher, start: CoroutineStart
= CoroutineStart.DEFAULT,. parent: Job? = null, block: suspend CoroutineScope.() -> Unit ): Job. START NOW OR LAZILY? -
public actual fun launch( context: CoroutineContext = DefaultDispatcher, start: CoroutineStart
= CoroutineStart.DEFAULT, parent: Job? = null, block: suspend CoroutineScope.() -> Unit ): Job SPECIFY A PARENT COROUTINE -
public actual fun launch( context: CoroutineContext = DefaultDispatcher, start: CoroutineStart
= CoroutineStart.DEFAULT, parent: Job? = null, block: suspend CoroutineScope.() -> Unit. ): Job THE FUNCTION TO RUN -
val deferred = async(context = CommonPool) {. loadTweets("#AndroidMakers"). }. launch(context
= UI) {. showTweets(deferred.await()). }. deferred.cancel(). Will throw CancellationException! -
// Launch a coroutine that returns a deferred value val
deferred: Deferred<List<Tweet>> = async { loadTweets("#AndroidMakers") } // Fire and forget! val job: Job = launch { loadTweets("#AndroidMakers") } -
SUSPENDED FUNCTION interface Continuation<in T> { val context: CoroutineContext fun
resume(value: T) fun resumeWithException(exception: Throwable) } -
SUSPENDED FUNCTION suspend fun <T> CompletableFuture<T>.await(): T = suspendCoroutine<T> {
cont: Continuation<T> -> 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) } } -
fun <T> Activity.load(loadFunction: () -> T) {. // TODO perform
background loading here. }. -
fun <T> Activity.load(loadFunction: () -> T): Deferred<T> {. return async
{ loadFunction() }. }. -
fun <T> Activity.load(loadFunction: () -> T): Deferred<T> {. return async
{ loadFunction() }. }. . fun <T> Deferred<T>.then(uiFunction: (T) -> Unit) {. launch(UI) { uiFunction([email protected]()) }. }. -
fun <T> Activity.load(loadFunction: () -> T): Deferred<T> {. return async
{ loadFunction() }. }. . infix fun <T> Deferred<T>.then(uiFunction: (T) -> Unit) {. launch(UI) { uiFunction([email protected]()) }. }. -
override fun onStart() { super.onStart() load { loadTweets("#AndroidMakers") } then
{ showTweets(it) } } ALMOST THERE! -
LIFECYCLE OBSERVER class CoroutineLifecycleListener(val job: Job) : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() { if(!job.isCancelled) job.cancel() } } -
fun <T> Activity.load(loadFunction: () -> T): Deferred<T> {. return asynco{oloadFunction()o}o
}. . infix fun <T> Deferred<T>.then(uiFunction: (T) -> Unit) {. launch(context = UI) {. uiFunction([email protected]()). }. }. -
fun <T> LifecycleOwner.load(loadFunction: () -> T): Deferred<T> {. val deferred
= asynco{oloadFunction()o}o lifecycle.addObserver(CoroutineLifecycleListener(deferred)). return deferred. }. . infix fun <T> Deferred<T>.then(uiFunction: (T) -> Unit) {. launch(context = UI) {. uiFunction([email protected]()). }. }. -
val loaderContext: CoroutineContext = newFixedThreadPoolContext(2, "loader") fun <T> LifecycleOwner.load(context: CoroutineContext
= loaderContext, loadFunction: () -> T): Deferred<T> { val deferred = async(context = context, start = CoroutineStart.LAZY) { loadFunction() } lifecycle.addObserver(CoroutineLifecycleListener(deferred)) return deferred } infix fun <T> Deferred<T>.then(uiFunction: (T) -> Unit) { launch(context = UI) { uiFunction([email protected]()) } } MORE CONTROL -
val loaderContext: CoroutineContext = newFixedThreadPoolContext(2, "loader") fun <T> LifecycleOwner.load(context: CoroutineContext
= loaderContext, loadFunction: () -> T): Deferred<T> { val deferred = async(context = context, start = CoroutineStart.LAZY) { loadFunction() } lifecycle.addObserver(CoroutineLifecycleListener(deferred)) return deferred } infix fun <T> Deferred<T>.then(uiFunction: (T) -> Unit) { launch(context = UI) { uiFunction([email protected]()) } } MORE CONTROL -
val loaderContext: CoroutineContext = newFixedThreadPoolContext(2, "loader") fun <T> LifecycleOwner.load(context: CoroutineContext
= loaderContext, loadFunction: () -> T): Deferred<T> { val deferred = async(context = context, start = CoroutineStart.LAZY) { loadFunction() } lifecycle.addObserver(CoroutineLifecycleListener(deferred)) return deferred } infix fun <T> Deferred<T>.then(uiFunction: (T) -> Unit) { launch(context = UI) { uiFunction([email protected]()) } } MORE CONTROL -
override fun onStart() { super.onStart() load { loadTweets("#AndroidMakers") } then
{ showTweets(it) } } DONE! -
interface Continuation<in T> { val context: CoroutineContext fun resume(value: T)
funoresumeWithException(exception: Throwable) } -
interface Continuation<in T> { val context: CoroutineContext fun resume(value: T)
funoresumeWithException(exception: Throwable) } -
override fun onStart() {. super.onStart(). . load.{. loadTweets("#AndroidMakers"). }.then {.
try {. showTweets(it). } catch (e: Exception) {. showErrorMessage(e). }. }. }. -
// Create a channel for reading and writing numbers val
channel = Channel<Int>() // 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! -
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! -
CAN HAVE MULTIPLE CONSUMERS val clickChannel = Channel<View>() button.setOnClickListener {
view -> launch { clickChannel.send(view) } } repeat(10)_{_ launch(CommonPool)_{_ clickChannel.consumeEach_{_ val result = doHeavyWork()_ }_ }_ }_ -
…OR MULTIPLE PRODUCERS val resultChannel = Channel<Int>()_ _ repeat(10)_{_ launch(CommonPool)_{_
clickChannel.consumeEach_{_ val_result_=_doHeavyWork()_ resultChannel.send(result)_ }_ }_ }_ _ launch(UI)_{ resultChannel.consumeEach { updateUI(it) } } -
button.setOnClickListener { load { loadTweets(“#AndroidMakers") } then { showTweets(it) }
} How can I throttle the click callbacks? Launches a new coroutine on every click! -
val clickActor = actor<View>(UI) { channel.map(CommonPool) { loadTweets("#AndroidMakers") } .consumeEach
{ showTweets(it) } } button.setOnClickListener { clickActor.offer(it) } ... clickActor.close() Drop this event if the receiver is busy! -
class LoadingChannel<out T>(val lifecycle: Lifecycle,_ val view: View,_ val loadFunction:
() -> T) {_ infix fun then(uiFunction: (T) -> Unit) {_ val job = Job() val actor = actor<Unit>(context = UI, parent = job) { }_ _ lifecycle.addObserver(CoroutineLifecycleListener(job))_ _ view.setOnClickListener { actor.offer(Unit) }_ }_ }_ -
class LoadingChannel<out T>(val lifecycle: Lifecycle,_ val view: View,_ val loadFunction:
() -> T) {_ infix fun then(uiFunction: (T) -> Unit) {_ val job = Job() val actor = actor<Unit>(context = UI, parent = job) { channel.map(CommonPool) { loadFunction() }_ .consumeEach { uiFunction(it) }_ }_ _ lifecycle.addObserver(CoroutineLifecycleListener(job))_ _ view.setOnClickListener { actor.offer(Unit) }_ }_ }_ -
class LoadingChannel<out T>(val lifecycle: Lifecycle,_ val view: View,_ val loadFunction:
() -> T) {_ infix fun then(uiFunction: (T) -> Unit) {_ val job = Job() val actor = actor<Unit>(context = UI, parent = job) { channel.map(CommonPool) { loadFunction() }_ .consumeEach { uiFunction(it) }_ }_ _ lifecycle.addObserver(ActorLifecycleListener(job))_ _ view.setOnClickListener { actor.offer(Unit) }_ }_ }_ -
fun <T> LifecycleOwner.whenClicking(view: View, loadFunction: () -> T) : LoadingChannel<T>
{ return LoadingChannel<T>(lifecycle, view, loadFunction) } -
override fun onCreate(savedInstanceState: Bundle?) {_ super.onCreate(savedInstanceState)_ setContentView(R.layout.activity_main)_ _ whenClicking(button) {_
loadTweets("#AndroidMakers")_ }_then {_ showTweets(it)_ }_ }_ -
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<User> // or @GET("/user") fun getUser(): Deferred<Response<User>> } -
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" } -
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