Share
Embed
Introduction to Kotlin Coroutines
Introduction to kotlin coroutines, talk given at Berlin Android Monthly meetup @Berlindroid
Adegeye Mayowa
December 07, 2018
Transcript
109 slides
-
fun login(username: String, password: String): User fun getOrders(userId: String): List<Orders>
fun fetchUserOrders() { val user = login(username, password) val orders = getOrders(user.userId) showUserOrders(orders) } -
fun login(username: String, password: String): User fun getOrders(userId: String): List<Orders>
fun fetchUserOrders() { val user = login(username, password) val orders = getOrders(user.userId) showUserOrders(orders) } I/O calls -
fun login(username: String, password: String): User fun getOrders(userId: String): List<Orders>
fun fetchUserOrders() { val user = login(username, password) val orders = getOrders(user.userId) showUserOrders(orders) } UI thread -
Callback fun fetchUserOrders(username: String, password: String) { login(username, password) {
user -> getOrders(user.userId) { orders -> showUserOrders(orders) } } } -
RxJava fun fetchUserOrders(username: String, password: String) { login(username, password) .flatMap
{ user → getOrders(user.userId) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.main()) .subscribe({orders -> showUserOrders(orders)}) } -
Is it possible to write async code in a sequential
manner without getting lost in the implementation details ? -
What is a coroutine • A lightweight thread that can
run a computation without blocking. -
What is a coroutine • A lightweight thread that can
run a computation without blocking. • It can be suspended and resumed at a later time. -
What is a coroutine • A lightweight thread that can
run a computation without blocking. • It can be suspended and resumed at a later time. • Suspension points are defined by the programmer. -
Key Coroutine Concepts • Suspending functions • Coroutine Dispatchers •
Coroutine Builders -
Suspending function • A function that can suspend the execution
of a coroutine • It can be started, paused and resumed at a later time -
Suspending function...contd • They can only be called within a
coroutine or from another suspending function -
Suspending function • They can only be called within a
coroutine or from another suspending function • They can take parameters and have return types -
fun doHeavyComputation(param: Int,callback:Continuation<Int>) interface Continuation<in T> { public val context:
CoroutineContext public fun resumeWith(result: Result<T>) } fun<T> Continuation<T>.resume(value: T) { } fun<T> Continuation<T>.resumeWithException(exception: Throwable) -
Coroutine Dispatchers • CoroutineContext Element that determines the thread a
coroutine runs on. • It can confine a coroutine to a specific thread, a threadpool or let it run unconfined. -
Kotlinx.coroutines dispatchers • Dispatchers.DEFAULT • Dispatchers.IO • Dispatchers.UNCONFINED • Dispatchers.MAIN
• newFixedThreadPoolContext & newSingleThreadContext -
Coroutine Builders Acts as the bridge that allows us to
call suspending functions from our code. -
Coroutine Builders Acts as the bridge that allows us to
call suspending functions from our code. • launch - fire and forget -
Coroutine Builders Acts as the bridge that allows us to
call suspending functions from our code. • launch - fire and forget • async - returns a Deferred<T> -
launch fun CoroutineScope.launch( context: CoroutineContext = EmptyCoroutineContext, Start: CoroutineStart =
CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job -
async fun <T> CoroutineScope.async( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart
= CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T ): Deferred<T> -
Async • You need to call await() on the returned
Deferred<T> to get the actual result. -
Async • You need to call await() on the returned
Deferred<T> to get the actual result. • async...await can be used to run several tasks in parallel. -
suspend fun firstValue(): Int { delay(500) //delays for 500ms return
10 } suspend fun secondValue(): Int { delay(300) //delays for 300ms return 20 } -
suspend fun firstValue(): Int { delay(500) //delays for 500ms return
10 } suspend fun secondValue(): Int { delay(300) //delays for 300ms return 20 } fun main() = runBlocking { val time = measureTimeMillis { val first = async { firstValue() } val second = async { secondValue() } val sum = first.await() + second.await() } println(time) } -
suspend fun firstValue(): Int { delay(500) //delays for 500ms return
10 } suspend fun secondValue(): Int { delay(300) //delays for 300ms return 20 } fun main() = runBlocking { val time = measureTimeMillis { val first = async { firstValue() } val second = async { secondValue() } val sum = first.await() + second.await() } println(time) } -
suspend fun firstValue(): Int { delay(500) //delays for 500ms return
10 } suspend fun secondValue(): Int { delay(300) //delays for 300ms return 20 } fun main() = runBlocking { val time = measureTimeMillis { val first = async { firstValue() } val second = async { secondValue() } val sum = first.await() + second.await() } println(time) } -
suspend fun firstValue(): Int { delay(500) //delays for 500ms return
10 } suspend fun secondValue(): Int { delay(300) //delays for 300ms return 20 } fun main() = runBlocking { val time = measureTimeMillis { val first = async { firstValue() } val second = async { secondValue() } val sum = first.await() + second.await() } println(time) //prints 518 } -
withContext Can be used to run a block of code
that returns in a value in another context. -
withContext Can be used to run a block of code
that returns in a value in another context. It suspends until completion and returns the result -
withContext public suspend fun <T> withContext( context: CoroutineContext, block: suspend
CoroutineScope.() -> T ): T -
Get user orders revisited fun login(username: String, password: String): User
fun getOrders(userId: String): List<Orders> fun fetchUserOrders() { val user = login(username, password) val orders = getOrders(user.userId) showUserOrders(orders) } -
Get user orders revisited suspend fun login(username: String, password: String):
User { return withContext(Dispatcher.IO) { //returns User } } -
Get user orders revisited suspend fun login(username: String, password: String):
User { return withContext(Dispatcher.IO) { //returns User } } suspend fun getOrders(userId: String): List<Orders> { return withContext(Dispatchers.IO) { //return list of orders } } -
Get user orders revisited fun fetchUserOrders() = GlobalScope.launch(Dispatchers.MAIN){ val user
= login(username, password) val orders = getOrders(user.userId) showUserOrders(orders) } -
Get user orders revisited fun fetchUserOrders() = GlobalScope.launch(Dispatchers.MAIN){ val user
= login(username, password) //first suspension point val orders = getOrders(user.userId) showUserOrders(orders) } -
Get user orders revisited fun fetchUserOrders() = GlobalScope.launch(Dispatchers.MAIN){ val user
= login(username, password) val orders = getOrders(user.userId) //second suspension point showUserOrders(orders) } -
Get user orders revisited fun fetchUserOrders() = GlobalScope.launch(Dispatchers.MAIN){ val user
= login(username, password) val orders = getOrders(user.userId) showUserOrders(orders) } back on main thread and can update the UI -
Structured concurrency • All coroutine builders are extension function of
CoroutineScope • We need to be able to keep track of all coroutines launched -
Structured concurrency • All coroutine builders are extension function of
CoroutineScope • We need to be able to keep track of all coroutines launched • CoroutineScope should be implemented by an object with a lifeycle i.e Activity, Fragment, ViewModel -
class MainActivity: AppCompatActivity(), CoroutineScope { override val coroutineContext: CoroutineContext get()
= Dispatchers.Main private fun loadData() { } } -
class MainActivity: AppCompatActivity(), CoroutineScope { private lateint var job override
val coroutineContext: CoroutineContext get() = Dispatchers.Main private fun loadData() { } } -
class MainActivity: AppCompatActivity(), CoroutineScope { private lateint var job override
val coroutineContext: CoroutineContext get() = Dispatchers.Main override fun onCreate(savedInstanceState: Bundle?) { job = Job() } private fun loadData() { } } -
class MainActivity: AppCompatActivity(), CoroutineScope { private lateint var job override
val coroutineContext: CoroutineContext get() = Dispatchers.Main override fun onCreate(savedInstanceState: Bundle?) { job = Job() } override fun onDestroy() { job.cancel() } } -
class MainActivity: AppCompatActivity(), CoroutineScope { private lateint var job override
val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override fun onCreate(savedInstanceState: Bundle?) { job = Job() } override fun onDestroy() { job.cancel() } } -
class MainActivity: AppCompatActivity(), CoroutineScope { private lateint var job override
val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override fun onCreate(savedInstanceState: Bundle?) { job = Job() } override fun onDestroy() { job.cancel() } } -
Conventions • Functions declared as extension function on CoroutineScope should
return immediately and executes its task concurrently with the rest of the program. -
Conventions • Functions declared as extension function on CoroutineScope should
return immediately and executes its task concurrently with the rest of the program. • Suspending functions should do its task separately in another context and return to caller when done. It should not block the caller. -
Conventions • Suspending functions should do its task separately in
another context and return to caller when done. It should not block the caller. • Functions should not be both suspending and an extension function on coroutine scope. -
Do this fun CoroutineScope.launchBackgroundWork() = launch { } suspend fun
doIOWork() = withContext(Dispatchers.IO) { } -
Exception Handling • Wrap suspend functions or deferred.await() in a
try..catch block -
Exception Handling • Wrap suspend functions or deferred.await() in a
try..catch block • Launch coroutine builder propagates exceptions as an unhandled exception, while async exposes the exception to the user to consume. -
val job = GlobalScope.launch { println("Throwing exception from launch") throw
IndexOutOfBoundsException() } val deferred = GlobalScope.async { println("Throwing exception from async") throw ArithmeticException() } -
val job = GlobalScope.launch { println("Throwing exception from launch") throw
IndexOutOfBoundsException() //exception will be printed to console } val deferred = GlobalScope.async { println("Throwing exception from async") throw ArithmeticException() // Nothing is printed, relying on user to call await } -
val deferred = GlobalScope.async { println("Throwing exception from async") throw
ArithmeticException() // Nothing is printed, relying on user to call await } try { deferred.await() println("Unreached") } catch (e: ArithmeticException) { println("Caught ArithmeticException") //printed to the console } -
use CoroutineExceptionHandler context element as a generic handler for all
uncaught exceptions. -
val exceptionHandler = CoroutineExceptionHandler { _, exception -> println(“Caught: $exception")
} val job = GlobalScope.launch(exceptionHandler) { } -
val exceptionHandler = CoroutineExceptionHandler { _, exception -> println(“Caught: $exception")
} val job = GlobalScope.launch(exceptionHandler) { throw IOException(“error occurred”) } //console output: Caught: java.io.IOException: error occurred -
CoroutineExceptionHandler is only invoked on exceptions that are not expected
to be handled by the user -
val exceptionHandler = CoroutineExceptionHandler { _, exception -> println(“Caught: $exception")
} val job = GlobalScope.async(exceptionHandler) { throw IndexOutOfBoundsException(“error occurred”) } //exception will be swallowed and nothing printed to the console -
Testing Make your viewmodels, use cases or repositories explicitly take
a Dispatcher and provide a replacement in your test. -
data class DispatcherProvider( val io: CoroutineDispatcher, val computation: CoroutineDispatcher, val
main: CoroutineDispatcher ) -
data class DispatcherProvider( val io: CoroutineDispatcher, val computation: CoroutineDispatcher, val
main: CoroutineDispatcher ) @Provides @Singleton fun providesDispatchersProvider() = DispatcherProvider( io = Dispatchers.IO, computation = Dispatchers.Default, main = Dispatchers.Main ) -
class FetchMoviesUseCase(private val moviesApi: MoviesApi, private val dispatcherProvider: DispatcherProvider) {
suspend fun movies(): List<Movies> { return withContext(dispatcherProvider.io) { moviesApi.getMovies() } } } -
use Unconfined Dispatcher in test @Provides @Singleton fun providesTestDispatchers() =
DispatcherProvider( io = Dispatchers.Unconfined, computation = Dispatchers.Unconfined, main = Dispatchers.Unconfined ) -
TestCoroutineContext • use TestCoroutineContext if you deal with delays and
timeout in your test. -
TestCoroutineContext • use TestCoroutineContext if you deal with delays and
timeout in your test. • Similar to TestScheduler in RxJava -
TestCoroutineContext • use TestCoroutineContext if you deal with delays and
timeout in your test. • Similar to TestScheduler in RxJava • advanceTimeBy -
TestCoroutineContext • use TestCoroutineContext if you deal with delays and
timeout in your test. • Similar to TestScheduler in RxJava • advanceTimeBy • advanceTimeTo -
TestCoroutineContext • use TestCoroutineContext if you deal with delays and
timeout in your test. • Similar to TestScheduler in RxJava • advanceTimeBy • advanceTimeTo • triggerActions -
Further Reading Google Coroutines code lab Kotlin Coroutines guide Structured
Concurrency by Roman Elizarov