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

Coroutines And Flow

Coroutines And Flow

An introduction to Kotlin Coroutines and Flow apis

José Caique Oliveira

June 15, 2019
Tweet

More Decks by José Caique Oliveira

Other Decks in Technology

Transcript

  1. A PROGRAM IS A SET OF OPERATIONS TO A COMPUTER

    TO PERFORM. A COMPUTER PROGRAM BECOMES A PROCESS WHEN IT IS LOADED AND BEGINS EXECUTION
  2. A THREAD IS A SEQUENCE OF SUCH INSTRUCTIONS WITH A

    PROGRAM THAT CAN BE EXECUTED INDEPENDENTLY OF OTHER CODE
  3. fun main() = runBlocking { val jobs = List(100_000) {

    launch { delay(1000L) print(".") } } jobs.forEach { it.join() } } java.lang.OutOfMemoryError fun main() { val jobs = List(100_000) { thread { sleep(1000L) print(".") } } jobs.forEach { it.join() } } COROUTINES THREADS
  4. class MyActivity : Activity(), CoroutineScope by MainScope() { override fun

    onDestroy() { cancel() } } class MyViewModel : ViewModel(), CoroutineScope { override val coroutineContext: CoroutineContext = Main override fun onCleared() { super.onCleared() cancel() } } class MyViewModel : ViewModel() { init { viewModelScope.launch { ... } } }
  5. EXECUTION OF THE CODE WITHOUT BLOCKING THE CURRENT THREAD OF

    EXECUTION. A SUSPENDING FUNCTION CANNOT BE INVOKED FROM A REGULAR CODE, BUT ONLY FROM OTHER SUSPENDING FUNCTIONS AND FROM SUSPENDING LAMBDAS
  6. SUSPENDING FUNCTIONS DO NOT BLOCK THE CALLER THREAD. SUSPENDING FUNCTIONS

    HAVE THE ABILITY TO BLOCK THE EXECUTION OF THE COROUTINE
  7. suspend fun doRequest() : Int { return 1 } suspend

    fun doRequest(): Int = withContext(IO) { 1 } //withTimeout(1000L){ ... }

  8. fun retrieve() : Int { doRequest() } suspend fun doRequest():

    Int = withContext(IO) { 1 //some result here } Suspend function 'performRequest' should be called only from a coroutine or another suspend function
  9. runBlocking{ viewState.value = ScreenState.Loading viewState.value = performRequest() } @Test fun

    testSuspendingFunction() = runBlocking { val res = suspendingTask1() assertEquals(0, res) }
  10. val result : Deferred<T> = viewModelScope.async { viewState.value = ScreenState.Loading

    viewState.value = performRequest() } result.await() //blocking
 result.cancel()
  11. viewModelScope.launch(Main) { val user = withContext(IO) { userService.doLogin(username, password) }

    val currentFriends = withContext(IO) { userService.requestCurrentFriends(user) } val suggestedFriends = withContext(IO) { userService.requestSuggestedFriends(user) } val finalUser = user.copy( friends = currentFriends + suggestedFriends) }
  12. viewModelScope.launch(Main) { val user = withContext(IO) { userService.doLogin(username, password) }

    val currentFriends = async(IO) { userService.requestCurrentFriends(user) } val suggestedFriends = async(IO) { userService.requestSuggestedFriends(user) } val finalUser = user.copy( friends = currentFriends + suggestedFriends) }
  13. suspend fun login(name: String, psw: String): User = suspendCancellableCoroutine {

    continuation -> service.doLogin(username, password) { user -> continuation.resume(user) } } //continuation.resumeWithException(error)
  14. KOTLIN REACTIVE PROGRAMMING COLD STREAMS + COROUTINES + OPERATORS SIMILAR

    TO SEQUENCES, FLOWS CAN BE TRANSFORMED USING VARIOUS COMMON OPERATORS LIKE MAP, FILTER, ETC UNLIKE A SEQUENCE, A FLOW IS ASYNCHRONOUS AND ALLOWS SUSPENDING FUNCTIONS ANYWHERE IN ITS BUILDER AND OPERATORS
  15. fun foo(p: Params): Flow<Value> = flow { while (hasMore) emit(nextValue)

    } val ints: Flow<Int> = flow { for (i in 1..10) { delay(100) emit(i) } } ints.collect { println(it) }
  16. fun <T> Flow<T>.delayASecond() = flow { collect { value ->

    // collect from the original flow delay(1000) // delay 1 second emit(value) // emit value to the resulting flow } }
  17. val broadcast: ConflatedBroadcastChannel<User> // emitting launch { broadcast.send(mMap.getBounds()) } //

    listening broadcast.consumeEach { service .retrieve(it) .map { it.getOrNull() } .collect { it?.let { … } } } //close broadcast.close()
  18. JOSÉ CAIQUE ▸ Software Engineer ▸ Computer Science by UFS

    ▸ Android Tech Lead at Stone ▸ Speaker
  19. J C A I Q U E _ J O

    S E C A I Q U E J O S E C A I Q U E T H A N K S
  20. REFERENCES ▸ http://www.inf.puc-rio.br/~roberto/docs/MCC15-04.pdf ▸ https://searchsoftwarequality.techtarget.com/definition/program ▸ https://stackoverflow.com/questions/43021816/difference-between-thread- and-coroutine-in-kotlin ▸ https://github.com/Kotlin/KEEP/blob/master/proposals/coroutines.md

    ▸ https://kotlinlang.org/docs/reference/coroutines/basics.html ▸ https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055 ▸ https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/ kotlinx.coroutines/-coroutine-scope/ ▸ https://skillsmatter.com/skillscasts/12727-coroutines-by- example#showModal?modal-signup-complete ▸ https://antonioleiva.com/coroutines/ ▸ https://sourcediving.com/kotlin-coroutines-in-android-e2d5bb02c275 ▸ https://medium.com/@elizarov/simple-design-of-kotlin-flow-4725e7398c4c