entendendo o conceito kotlin coroutines - amazon s3 · 2019-07-19 · kotlin coroutines entendendo...

32
1 Kotlin Coroutines Entendendo o Conceito Angélica Oliveira

Upload: others

Post on 10-Aug-2020

18 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

1

Kotlin Coroutines Entendendo o ConceitoAngélica Oliveira

Page 2: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

ANGÉLICA OLIVEIRA

MOBILE DEVELOPER @THOUGHTWORKS

2

LinkedIn: angelica-oliv

Page 3: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Sobre o que vamos falar?

- Por que Coroutines?

- Coroutine Builders

- Suspending Functions

- Coroutine Context e Dispatchers

- Testes com Coroutines3

Page 4: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Por que Coroutines?

4

Page 5: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

COROUTINE BUILDERS

5

Page 6: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Coroutines BuildersrunBlocking

6

fun main() { println("Hello,")

// block the main thread runBlocking { // now we are inside a coroutine delay(2000L) // suspends for 2 seconds }

// will be executed after 2 seconds println("Coroutines!")}

Page 7: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Coroutines Builderslaunch

7

fun main() { GlobalScope.launch { // launch new coroutine in background and continue delay(1000L) println("Coroutines!") }

println("Hello,") // main thread continues here immediately

runBlocking { delay(2000L) // ... 2 seconds to keep JVM alive }}

Page 8: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Coroutines Buildersasync

8

fun main() { val deferredResult: Deferred<String> = GlobalScope.async { // suspend for 1 second delay(1000L) // this is the result "Coroutine!" }

runBlocking { println("Hello") // wait for the result println(deferredResult.await()) }}

Page 9: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

SUSPENDING FUNCTIONS

9

Page 10: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Suspending FunctionsBlocking x Suspending

10

Page 11: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Suspending FunctionsBlocking x Suspending

11

Page 12: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Suspending FunctionsPor default coroutines são sequenciais

12

private suspend fun doSomethingUsefulOne(): Int {

delay(1000L) // pretend we are doing something useful here

return 13

}

private suspend fun doSomethingUsefulTwo(): Int {

delay(1000L) // pretend we are doing something useful here, too

return 29

}

Page 13: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Suspending FunctionsPor default coroutines são sequenciais

13

fun main() = runBlocking {

val time = measureTimeMillis {

val one = doSomethingUsefulOne()

val two = doSomethingUsefulTwo()

println("The answer is ${one + two}")

}

println("Completed in $time ms")

}

The answer is 42Completed in 2014 ms

Page 14: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Suspending FunctionsPor default coroutines são sequenciais

14

fun main() = runBlocking {

val time = measureTimeMillis {

val one = async { doSomethingUsefulOne() }

val two = async { doSomethingUsefulTwo() }

println("The answer is ${one.await() + two.await()}")

}

println("Completed in $time ms")

}The answer is 42

Completed in 1020 ms

Page 15: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

COROUTINE CONTEXT E DISPATCHERS

15

Page 16: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

- Coroutines sempre executam em um determinado contexto definido pelo tipo CoroutineContext

- O contexto da Coroutine é um conjunto de vários elementos, os principais são:

- Job- Dispatcher

16

Coroutines Context

Page 17: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

- Jobs são executáveis que possuem um ciclo de vida

- Podem possuir uma hierarquia parent-child

- Os estados de um Job são definidos pelas flags: - isActive- isCompleted- isCancelled

17

Coroutines ContextJob

Page 18: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

18

Coroutines ContextJob

Page 19: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

- Responsável por determinar que Thread ou Threads a Coroutine usa para sua execução

- Todos os builders de Coroutine aceitam um CoroutineContext como parâmetro, para explicitamente especificar o Dispatcher e outros elementos do contexto

19

Coroutines ContextDispatcher

Page 20: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

launch { ... }

launch(Dispatchers.Unconfined) { ... }

launch(Dispatchers.Default) { ... }

launch(newSingleThreadContext("MyOwnThread")) { ... }

20

Coroutines ContextDispatcher

Unconfined : I'm working in thread main

Default : I'm working in thread DefaultDispatcher-worker-2

newSingleThreadContext: I'm working in thread MyOwnThread

main runBlocking : I'm working in thread main

Page 21: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

COROUTINES SCOPE

21

Page 22: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Coroutines ScopeGlobal Scope

22

fun main() = runBlocking { GlobalScope.launch { repeat(1000) { i -> println("I'm sleeping $i ...") delay(500L) } } delay(1300L) // just quit after delay}

I'm sleeping 0 ...I'm sleeping 1 ...I'm sleeping 2 ...

Page 23: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Coroutines ScopeScope builder

23

fun main() = runBlocking { // this: CoroutineScope coroutineScope { // Creates a coroutine scope launch { delay(500L) println("Task from nested launch") }

delay(100L) println("Task from coroutine scope") }}

Page 24: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

COROUTINES TESTS

24

Page 25: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

- Chamada que sobrescreve o Main Dispatcher em situações de testes

- Pode ser utilizado quando:- Main dispatcher não está disponível- É necessário sobrescrever por questões de sincronia

dos testes (com uma implementação de um Dispatcher na classe de testes)

25

Coroutines TestsDispatcher.setMain

Page 26: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

// overrides Main Dispatcher with a test implementation

Dispatchers.setMain(dispatcherImplementation)

// reset Main Dispatcher with original implementationDispatchers.resetMain()

26

Coroutines TestsDispatcher.setMain

Page 27: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

Provê controle extra para testar as coroutines:

- Avanço do tempo automático para suspend functions- Avanço do tempo manual para testar coroutines múltiplas- Execução pausada de chamadas async e launch- Pausa, avanço ou recomeço das coroutines em um teste- Reportar exceções como falhas de testes

27

Coroutines TestsrunBlockingTest

Page 28: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

- TestCoroutineScope provê controle detalhado da execução das coroutines nos testes

- TestCoroutineDispatcher é o dispatcher utilizado quando se executa uma coroutine com TestCoroutineScope

- Ambos se integram com runBlockingTest

28

Coroutines TestsTestCoroutineScope e TestCoroutineDispatcher

Page 29: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

CÓDIGOUTILIZADO NA PALESTRA ;)

https://github.com/angelica-oliv/coroutines-basics

29

Page 30: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

http://bit.ly/tw-tdcsp-vagas

Quer se tornar uma ThoughtWorker?

/careers

Page 31: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

PERGUNTAS?

31

Page 32: Entendendo o Conceito Kotlin Coroutines - Amazon S3 · 2019-07-19 · Kotlin Coroutines Entendendo o Conceito Angélica Oliveira. ANGÉLICA OLIVEIRA MOBILE DEVELOPER @THOUGHTWORKS

OBRIGADA

32

ANGÉLICA OLIVEIRASENIOR CONSULTANT DEVELOPER

[email protected] | thoughtworks.com