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

Demystifying Coroutines

Demystifying Coroutines

Imagine as a human being if you did not multitask. Or when breathing your brain stopped working, or if you looked at a movie, you could not hear but only could see the images then afterwards you watched the movie. Or you received the audio some 2 minutes later.
Coroutines help in multitasking within a program. Not only Unique to Kotlin, though, this talk takes you from how the term was coined up until how you can implement one.

Frank Tamre

January 26, 2019
Tweet

More Decks by Frank Tamre

Other Decks in Technology

Transcript

  1. 2.Definition of Coroutines 3. Using Coroutines 4. Kotlin Coroutines 5.

    Code sample 1. Brief History of Coroutines Agenda
  2. 2.Go to that function and create a suspend instance: fun

    suspendableLambda(block: suspend () -> Unit)
  3. suspend fun validateEntries(str: String): Boolean = coroutineScope { val deferred1

    = async { firstValidation(str) } val deferred2 = async { secondValidation(str) } deferred1.await() && deferred2.await() }
  4. fun <A> inTransaction(f: (Connection) -> CompletableFuture<A>) : CompletableFuture<A> { return

    this.sendQuery("BEGIN").flatMap { _ -> val p = CompletableFuture<A>() f(this).onComplete { ty1 -> sendQuery( if (ty1.isFailure) "ROLLBACK" else "COMMIT") .onComplete { ty2 -> if (ty2.isFailure && ty1.isSuccess) p.failed((ty2 as Failure).exception) else p.complete(ty1) } } p } } With Callbacks
  5. suspend fun <A> inTransaction( f: suspend (Connection) -> A): A

    { try { this.sendQuery("BEGIN") val result = f(this) this.sendQuery("COMMIT") return result } catch (e: Throwable) { this.sendQuery("ROLLBACK") throw e } } with coroutines