Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Programação Assíncrona com Kotlin Coroutines

Programação Assíncrona com Kotlin Coroutines

Wellington Costa

December 05, 2018
Tweet

More Decks by Wellington Costa

Other Decks in Technology

Transcript

  1. Wellington Costa Pereira • +4 anos de experiência • Mestrando

    em Ciências da Computação • Android Leader na Resource IT Solutions • Open source <3 • Compartilhar conhecimento <3 GitHub: https://github.com/WellingtonCosta E-mail: [email protected]
  2. Exemplo fun updateUserData(username: String) { val user = fetchUserFromApi(username) val

    repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) }
  3. Estilo Tradicional fun updateUserData(username: String) { val user = fetchUserFromApi(username)

    val repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) }
  4. Estilo Tradicional fun updateUserData(username: String) { val user = fetchUserFromApi(username)

    val repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) }
  5. Estilo Tradicional fun updateUserData(username: String) { val user = fetchUserFromApi(username)

    val repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) }
  6. Coroutines suspend fun updateUserData(username: String) { val user = fetchUserFromApi(username)

    val repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) }
  7. Coroutines suspend fun updateUserData(username: String) { val user = fetchUserFromApi(username)

    val repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) }
  8. Principais Conceitos • Modificador suspend • launch vs async •

    Dispatchers • withContext • coroutineScope • runBlocking
  9. Modificador suspend A suspending function is simply a function that

    can be paused and resumed at a later time. They can execute a long running operation and wait for it to complete without blocking.
  10. Modificador suspend suspend fun updateUserData(username: String) { val user =

    fetchUserFromApi(username) val repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) }
  11. launch vs async launch: A background job. Conceptually, a job

    is a cancellable thing with a life-cycle that culminates in its completion. It returns a Job instance. async: Deferred value is a non-blocking cancellable future. It’s a Job that has a result. It returns a Deferred instance.
  12. launch vs async private val jobs = ArrayList<Job>() fun doSomething()

    { jobs.add( launch { // do some operation } ) } override fun onCleared() { jobs.forEach { if(!it.isCancelled) it.cancel() } }
  13. launch vs async fun doSomething() { val deferred = async

    { // do some operation } val result = deferred.await() }
  14. launch vs async fun doSomething() { val result = async

    { // do some operation }.await() }
  15. Dispatchers • Dispatchers.Main: A coroutine dispatcher that is confined to

    the Main thread operating with UI objects. • Dispatchers.Default: A coroutine dispatcher to execute CPU-bound tasks. • Dispatchers.IO: A coroutine dispatcher that is designed for offloading blocking IO tasks to a shared pool of threads.
  16. withContext Calls the suspending block with a given coroutine context,

    suspends until it completes and then returns the result.
  17. withContext suspend fun updateUserData(username: String) { withContext(Dispatchers.IO) { val user

    = fetchUserFromApi(username) val repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) } }
  18. withContext suspend fun updateUserData(username: String) { withContext(Dispatchers.IO) { val user

    = fetchUserFromApi(username) val repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) } }
  19. withContext suspend fun updateUserData(username: String) { withContext(Dispatchers.IO) { val user

    = fetchUserFromApi(username) val repos = fetchReposFromApi(username) saveUserDataInDb(user, repos) } }
  20. coroutineScope This function is designed for a parallel decomposition of

    work. When any child coroutine in this scope fails, this scope fails and all the rest of the children are cancelled.
  21. coroutineScope suspend fun processPayments(): List<Payment> { coroutineScope { val payments

    = withContext(Dispatchers.IO) { async { loadPayments() } } val processedPayments = withContext(Dispatchers.Default) { async { calculateInterestRate(payments.await()) } } return processedPayments.await() } }
  22. runBlocking suspend fun processPayments(): List<Payment> { // load payments and

    calculate its interest rate } @Test fun myAwesomeTest() { val payments = processPayments() // assert payments interest rate }
  23. runBlocking suspend fun processPayments(): List<Payment> { // load payments and

    calculate its interest rate } @Test fun myAwesomeTest() = runBlocking { val payments = processPayments() // assert payments interest rate }