SlideShare a Scribd company logo
1 of 34
Download to read offline
HOW TO SAY GOODBYE TO THREADING
AND CALLBACK HELL
KOTLIN COROUTINES ON ANDROID
Sevil Guler - 12.04.2019
Sevil Güler
Senior Android Developer
Normal
Kotlin & Java
CI & CD
Sevil Guler - 12.04.2019
COROUTINES - KOTLIN 1.3
Sevil Guler - 12.04.2019
WHAT IS THE PROBLEM
progress.visibility = View.VISIBLE
userService.doLoginAsync(username, password) { user ->
userService.requestCurrentFriendsAsync(user) { friends ->
val finalUser = user.copy(friends = friends)
toast("User ${finalUser.name} has ${finalUser.friends.size} friends")
progress.visibility = View.GONE
}
}
Sevil Guler - 12.04.2019
WHAT IS THE PROBLEM
1. Do the second friends request after the first one
2. Run both requests at the same time and find a way to synchronize the callback results.
Sevil Guler - 12.04.2019
WHAT IS THE PROBLEM
progress.visibility = View.VISIBLE
userService.doLoginAsync(username, password) { user ->
userService.requestCurrentFriendsAsync(user) { currentFriends ->
userService.requestSuggestedFriendsAsync(user) { suggestedFriends ->
val finalUser = user.copy(friends = currentFriends + suggestedFriends)
progress.visibility = View.GONE
}
}
}
Sevil Guler - 12.04.2019
WHAT ARE COROUTINES?
▸ Like threads but better
▸ asynchronous code sequentially
▸ can be run using the same thread
▸ light-weight
▸ the limit is almost infinite.
▸ Based on the idea of suspending functions
▸ Safe place where suspending functions will not block the current
thread.
Sevil Guler - 12.04.2019
WHAT ARE COROUTINES?
fun withCoroutines() = runBlocking {
repeat(100000) { counter ->
launch {
print(" $counter")
}
}
}
fun withThread() = runBlocking {
repeat(100000) { counter ->
thread {
print(" $counter")
}
}
}
Sevil Guler - 12.04.2019
WHAT ARE COROUTINES?
coroutine {
progress.visibility = View.VISIBLE
val user = suspended { userService.doLogin(username, password) }
val currentFriends = suspended { userService.requestCurrentFriends(user) }
val finalUser = user.copy(friends = currentFriends)
progress.visibility = View.GONE
}
Coroutine builder
Sevil Guler - 12.04.2019
SUSPENDING FUNCTIONS
▸ Block the execution of the coroutine
val user = suspended { userService.doLogin(username, password) }
val currentFriends = suspended { userService.requestCurrentFriends(user) } 


▸ Can run on the same or a different thread
▸ Only run inside a coroutine or inside another suspending
function.
▸ suspend reserved word
Sevil Guler - 12.04.2019
SUSPENDING FUNCTIONS
suspend fun suspendingFunction() : Int {
// Long running task
return 0
}
coroutine {
progress.visibility = View.VISIBLE
….
}
PROBLEM
Sevil Guler - 12.04.2019
COROUTINE CONTEXT
▸ Set of rules and configurations
▸ Dispatcher
✴ Explicitly: we manually set the dispatcher that will be used
✴ By the coroutine scope
Sevil Guler - 12.04.2019
EXPLICITLY
coroutine(Dispatchers.Main) {
progress.visibility = View.VISIBLE
}
Sevil Guler - 12.04.2019
PROBLEM
coroutine(Dispatchers.Main) {
progress.visibility = View.VISIBLE
...
val user = suspended { userService.doLogin(username, password) }
val currentFriends = suspended { userService.requestCurrentFriends(user) }
…
}
Sevil Guler - 12.04.2019
WITHCONTEXT
suspend fun suspendedLgn(name,passwrd) = withContext(Dispatchers.IO){
userService.doLogin(.., ..)
}
coroutine(Dispatchers.Main) {
progress.visibility = View.VISIBLE
val user = withContext(Dispatchers.IO) { userService.doLogin(username, password) }
val currentFriends = withContext(Dispatchers.IO){ userService.requestCurrentFriends(user) }
}
Sevil Guler - 12.04.2019
DISPATCHERS
▸ Thread or Threads
▸ 1 thread can run multiple coroutines
Sevil Guler - 12.04.2019
DISPATCHERS
▸ Dispatcher.Default
▸ Dispatcher.IO
▸ Dispatcher.Unconfined
▸ Dispatcher.Main
Sevil Guler - 12.04.2019
HOW TO RUN COROUTINES - COROUTINES BUILDER
▸ runBlocking
▸ blocks the current thread 

▸ very helpful to test suspending tasks 

fun testSuspendingFunction() = runBlocking {
val res = suspendingTask1()
assertEquals(0, res)
}
Sevil Guler - 12.04.2019
HOW TO RUN COROUTINES - COROUTINES BUILDER
LAUNCH
GlobalScope.launch {
…..
}
▸ launch
▸ main builder
▸ won’t block the current thread
▸ always needs a scope
▸ returns a Job
Sevil Guler - 12.04.2019
JOBS HAVE A COUPLE OF INTERESTING FUNCTIONS
▸ job.join
▸ job.cancel
val job = GlobalScope.launch(Dispatchers.Main) {
doCoroutineTask()
val res1 = suspendingTask1()
val res2 = suspendingTask2()
process(res1, res2)
}
job.join()
Sevil Guler - 12.04.2019
ASYNC
GlobalScope.launch(Dispatchers.Main) {
val user = withContext(Dispatchers.IO) { userService.doLogin(username, password) }
val currentFriends = withContext(Dispatchers.IO{ userService.requestCurrentFriends(user) }
val suggestedFriends = withContext(Dispatchers.IO { userService.requestSuggestedFriends(user) }
val finalUser = user.copy(friends = currentFriends + suggestedFriends)
}
Sevil Guler - 12.04.2019
ASYNC
GlobalScope.launch(Dispatchers.Main) {
val user = withContext(Dispatchers.IO) { userService.doLogin(username, password) }
val currentFriends = async(Dispatchers.IO) { userService.requestCurrentFriends(user) }
val suggestedFriends = async(Dispatchers.IO) { userService.requestSuggestedFriends(user) }
val finalUser =currentFriends.await()+ suggestedFriends.await()
}
Sevil Guler - 12.04.2019
ASYNC
▸ several background tasks in parallel
▸ not a suspending function itself
▸ returns a specialized job that is called Deferred
▸ await(), which is the blocking one
Sevil Guler - 12.04.2019
SCOPES
▸ Global scope
▸ Implement CoroutineScope
Sevil Guler - 12.04.2019
GLOBAL SCOPE
GlobalScope.launch {
…..
}
▸ App lifecycle
▸ Think twice
▸ specific screen or component
Sevil Guler - 12.04.2019
IMPLEMENT COROUTINESCOPE
▸ override the coroutineContext
▸ configure: the dispatcher, and the job
▸ to identify the default dispatcher that the
coroutines will use
▸ cancel all pending coroutines at any moment
▸ plus(+) operation -> CombinedContext
the job is used as the parent of the coroutines created from this scope.
Dispatchers.Main + Dispatchers.IO == Dispatchers.IO
Sevil Guler - 12.04.2019
IMPLEMENT COROUTINESCOPE
class MainActivity : AppCompatActivity(), CoroutineScope {
private lateinit var job : Job
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
super.onCreate(savedInstanceState, persistentState)
job = Job()
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
}
Sevil Guler - 12.04.2019
COROUTINE CANCELATION
val job = launch {
try {
repeat(1000) { counter ->
print(" $counter")
delay(50L)
}
} catch (e: CancellationException) {
print(" CancellationExceptionn")
}
}
delay(1000L)
job.cancel()
job.join()
Sevil Guler - 12.04.2019
EXCEPTIONS
▸ An exception other than CancellationException in a coroutine
scope cancels its parent. 
▸ CoroutineExceptionHandler 
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception")
}
▸ If we want cancellation to be propagated only downwards we can
use SupervisorJob or supervisorScope.
Sevil Guler - 12.04.2019
EXCEPTIONS
fun main() = runBlocking {
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught $exception with suppressed ${exception.suppressed.contentToString()}")
}
val job = GlobalScope.launch(handler) {
launch {
try {
delay(Long.MAX_VALUE)
} finally {
throw ArithmeticException()
}
}
launch {
delay(100)
throw IOException()
}
delay(Long.MAX_VALUE)
}
job.join()
}
Caught java.io.IOException with suppressed [java.lang.ArithmeticException]
Sevil Guler - 12.04.2019
EXCEPTIONS
val supervisor = SupervisorJob()
with(CoroutineScope(supervisor)) {
val child1 = launch(handler) {
println("Child1 is failing")
throw AssertionError("child1 cancelled")
}
val child2 = launch {
child1.join()
println("Child1 cancelled: ${child1.isCancelled}")
println("Child2 isActive: $isActive")
try {
delay(Long.MAX_VALUE)
} finally {
println("Finally Child2 isActive: $isActive")
}
}
child1.join()
println("Cancelling supervisor")
supervisor.cancel()
child2.join()
}
Child1 is failing
Caught java.lang.AssertionError: child1 cancelled
Cancelling supervisor
Child1 cancelled: true
Child2 isActive: true
Finally Child2 isActive: false
Sevil Guler - 12.04.2019
WHAT IS NEXT?
▸ Channels
▸ Shared mutable state and concurrency
▸ Reactive streams with coroutines
….
Sevil Guler - 12.04.2019
Coroutines

More Related Content

Similar to Coroutines

Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Tino Isnich
 
5 Things I Wish I Knew About Gitlab CI
5 Things I Wish I Knew About Gitlab CI5 Things I Wish I Knew About Gitlab CI
5 Things I Wish I Knew About Gitlab CISebastian Witowski
 
Testing - Selenium? Rich-Clients? Containers?
Testing - Selenium? Rich-Clients? Containers?Testing - Selenium? Rich-Clients? Containers?
Testing - Selenium? Rich-Clients? Containers?Tobias Schneck
 
Automated release management with team city & octopusdeploy - NDC 2013
Automated release management with team city & octopusdeploy - NDC 2013Automated release management with team city & octopusdeploy - NDC 2013
Automated release management with team city & octopusdeploy - NDC 2013Kristoffer Deinoff
 
Drupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfDrupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfLuca Lusso
 
2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pagessparkfabrik
 
Learn jobDSL for Jenkins
Learn jobDSL for JenkinsLearn jobDSL for Jenkins
Learn jobDSL for JenkinsLarry Cai
 
The world of gradle - an introduction for developers
The world of gradle  - an introduction for developersThe world of gradle  - an introduction for developers
The world of gradle - an introduction for developersTricode (part of Dept)
 
Gradle - time for a new build
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new buildIgor Khotin
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfigVijay Shukla
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 
Continuous Integration with Robot Sweatshop
Continuous Integration with Robot SweatshopContinuous Integration with Robot Sweatshop
Continuous Integration with Robot SweatshopJustin Scott
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfigVijay Shukla
 
Is it time to migrate to Vue 3?
Is it time to migrate to Vue 3?Is it time to migrate to Vue 3?
Is it time to migrate to Vue 3?Denny Biasiolli
 
learn you some erlang - chap13 to chap14
learn you some erlang - chap13 to chap14learn you some erlang - chap13 to chap14
learn you some erlang - chap13 to chap14경미 김
 

Similar to Coroutines (20)

Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01Gradleintroduction 111010130329-phpapp01
Gradleintroduction 111010130329-phpapp01
 
5 Things I Wish I Knew About Gitlab CI
5 Things I Wish I Knew About Gitlab CI5 Things I Wish I Knew About Gitlab CI
5 Things I Wish I Knew About Gitlab CI
 
Testing - Selenium? Rich-Clients? Containers?
Testing - Selenium? Rich-Clients? Containers?Testing - Selenium? Rich-Clients? Containers?
Testing - Selenium? Rich-Clients? Containers?
 
Top5 scalabilityissues
Top5 scalabilityissuesTop5 scalabilityissues
Top5 scalabilityissues
 
Gradle how to's
Gradle how to'sGradle how to's
Gradle how to's
 
Automated release management with team city & octopusdeploy - NDC 2013
Automated release management with team city & octopusdeploy - NDC 2013Automated release management with team city & octopusdeploy - NDC 2013
Automated release management with team city & octopusdeploy - NDC 2013
 
Drupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdfDrupalcon 2023 - How Drupal builds your pages.pdf
Drupalcon 2023 - How Drupal builds your pages.pdf
 
2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages2023 - Drupalcon - How Drupal builds your pages
2023 - Drupalcon - How Drupal builds your pages
 
Learn jobDSL for Jenkins
Learn jobDSL for JenkinsLearn jobDSL for Jenkins
Learn jobDSL for Jenkins
 
The world of gradle - an introduction for developers
The world of gradle  - an introduction for developersThe world of gradle  - an introduction for developers
The world of gradle - an introduction for developers
 
Gradle - time for a new build
Gradle - time for a new buildGradle - time for a new build
Gradle - time for a new build
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfig
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 
Continuous Integration with Robot Sweatshop
Continuous Integration with Robot SweatshopContinuous Integration with Robot Sweatshop
Continuous Integration with Robot Sweatshop
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Is it time to migrate to Vue 3?
Is it time to migrate to Vue 3?Is it time to migrate to Vue 3?
Is it time to migrate to Vue 3?
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
learn you some erlang - chap13 to chap14
learn you some erlang - chap13 to chap14learn you some erlang - chap13 to chap14
learn you some erlang - chap13 to chap14
 

Recently uploaded

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 

Coroutines

  • 1. HOW TO SAY GOODBYE TO THREADING AND CALLBACK HELL KOTLIN COROUTINES ON ANDROID Sevil Guler - 12.04.2019
  • 2. Sevil Güler Senior Android Developer Normal Kotlin & Java CI & CD Sevil Guler - 12.04.2019
  • 3.
  • 4. COROUTINES - KOTLIN 1.3 Sevil Guler - 12.04.2019
  • 5. WHAT IS THE PROBLEM progress.visibility = View.VISIBLE userService.doLoginAsync(username, password) { user -> userService.requestCurrentFriendsAsync(user) { friends -> val finalUser = user.copy(friends = friends) toast("User ${finalUser.name} has ${finalUser.friends.size} friends") progress.visibility = View.GONE } } Sevil Guler - 12.04.2019
  • 6. WHAT IS THE PROBLEM 1. Do the second friends request after the first one 2. Run both requests at the same time and find a way to synchronize the callback results. Sevil Guler - 12.04.2019
  • 7. WHAT IS THE PROBLEM progress.visibility = View.VISIBLE userService.doLoginAsync(username, password) { user -> userService.requestCurrentFriendsAsync(user) { currentFriends -> userService.requestSuggestedFriendsAsync(user) { suggestedFriends -> val finalUser = user.copy(friends = currentFriends + suggestedFriends) progress.visibility = View.GONE } } } Sevil Guler - 12.04.2019
  • 8. WHAT ARE COROUTINES? ▸ Like threads but better ▸ asynchronous code sequentially ▸ can be run using the same thread ▸ light-weight ▸ the limit is almost infinite. ▸ Based on the idea of suspending functions ▸ Safe place where suspending functions will not block the current thread. Sevil Guler - 12.04.2019
  • 9. WHAT ARE COROUTINES? fun withCoroutines() = runBlocking { repeat(100000) { counter -> launch { print(" $counter") } } } fun withThread() = runBlocking { repeat(100000) { counter -> thread { print(" $counter") } } } Sevil Guler - 12.04.2019
  • 10. WHAT ARE COROUTINES? coroutine { progress.visibility = View.VISIBLE val user = suspended { userService.doLogin(username, password) } val currentFriends = suspended { userService.requestCurrentFriends(user) } val finalUser = user.copy(friends = currentFriends) progress.visibility = View.GONE } Coroutine builder Sevil Guler - 12.04.2019
  • 11. SUSPENDING FUNCTIONS ▸ Block the execution of the coroutine val user = suspended { userService.doLogin(username, password) } val currentFriends = suspended { userService.requestCurrentFriends(user) } 

 ▸ Can run on the same or a different thread ▸ Only run inside a coroutine or inside another suspending function. ▸ suspend reserved word Sevil Guler - 12.04.2019
  • 12. SUSPENDING FUNCTIONS suspend fun suspendingFunction() : Int { // Long running task return 0 } coroutine { progress.visibility = View.VISIBLE …. } PROBLEM Sevil Guler - 12.04.2019
  • 13. COROUTINE CONTEXT ▸ Set of rules and configurations ▸ Dispatcher ✴ Explicitly: we manually set the dispatcher that will be used ✴ By the coroutine scope Sevil Guler - 12.04.2019
  • 14. EXPLICITLY coroutine(Dispatchers.Main) { progress.visibility = View.VISIBLE } Sevil Guler - 12.04.2019
  • 15. PROBLEM coroutine(Dispatchers.Main) { progress.visibility = View.VISIBLE ... val user = suspended { userService.doLogin(username, password) } val currentFriends = suspended { userService.requestCurrentFriends(user) } … } Sevil Guler - 12.04.2019
  • 16. WITHCONTEXT suspend fun suspendedLgn(name,passwrd) = withContext(Dispatchers.IO){ userService.doLogin(.., ..) } coroutine(Dispatchers.Main) { progress.visibility = View.VISIBLE val user = withContext(Dispatchers.IO) { userService.doLogin(username, password) } val currentFriends = withContext(Dispatchers.IO){ userService.requestCurrentFriends(user) } } Sevil Guler - 12.04.2019
  • 17. DISPATCHERS ▸ Thread or Threads ▸ 1 thread can run multiple coroutines Sevil Guler - 12.04.2019
  • 18. DISPATCHERS ▸ Dispatcher.Default ▸ Dispatcher.IO ▸ Dispatcher.Unconfined ▸ Dispatcher.Main Sevil Guler - 12.04.2019
  • 19. HOW TO RUN COROUTINES - COROUTINES BUILDER ▸ runBlocking ▸ blocks the current thread 
 ▸ very helpful to test suspending tasks 
 fun testSuspendingFunction() = runBlocking { val res = suspendingTask1() assertEquals(0, res) } Sevil Guler - 12.04.2019
  • 20. HOW TO RUN COROUTINES - COROUTINES BUILDER LAUNCH GlobalScope.launch { ….. } ▸ launch ▸ main builder ▸ won’t block the current thread ▸ always needs a scope ▸ returns a Job Sevil Guler - 12.04.2019
  • 21. JOBS HAVE A COUPLE OF INTERESTING FUNCTIONS ▸ job.join ▸ job.cancel val job = GlobalScope.launch(Dispatchers.Main) { doCoroutineTask() val res1 = suspendingTask1() val res2 = suspendingTask2() process(res1, res2) } job.join() Sevil Guler - 12.04.2019
  • 22. ASYNC GlobalScope.launch(Dispatchers.Main) { val user = withContext(Dispatchers.IO) { userService.doLogin(username, password) } val currentFriends = withContext(Dispatchers.IO{ userService.requestCurrentFriends(user) } val suggestedFriends = withContext(Dispatchers.IO { userService.requestSuggestedFriends(user) } val finalUser = user.copy(friends = currentFriends + suggestedFriends) } Sevil Guler - 12.04.2019
  • 23. ASYNC GlobalScope.launch(Dispatchers.Main) { val user = withContext(Dispatchers.IO) { userService.doLogin(username, password) } val currentFriends = async(Dispatchers.IO) { userService.requestCurrentFriends(user) } val suggestedFriends = async(Dispatchers.IO) { userService.requestSuggestedFriends(user) } val finalUser =currentFriends.await()+ suggestedFriends.await() } Sevil Guler - 12.04.2019
  • 24. ASYNC ▸ several background tasks in parallel ▸ not a suspending function itself ▸ returns a specialized job that is called Deferred ▸ await(), which is the blocking one Sevil Guler - 12.04.2019
  • 25. SCOPES ▸ Global scope ▸ Implement CoroutineScope Sevil Guler - 12.04.2019
  • 26. GLOBAL SCOPE GlobalScope.launch { ….. } ▸ App lifecycle ▸ Think twice ▸ specific screen or component Sevil Guler - 12.04.2019
  • 27. IMPLEMENT COROUTINESCOPE ▸ override the coroutineContext ▸ configure: the dispatcher, and the job ▸ to identify the default dispatcher that the coroutines will use ▸ cancel all pending coroutines at any moment ▸ plus(+) operation -> CombinedContext the job is used as the parent of the coroutines created from this scope. Dispatchers.Main + Dispatchers.IO == Dispatchers.IO Sevil Guler - 12.04.2019
  • 28. IMPLEMENT COROUTINESCOPE class MainActivity : AppCompatActivity(), CoroutineScope { private lateinit var job : Job override val coroutineContext: CoroutineContext get() = job + Dispatchers.Main override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { super.onCreate(savedInstanceState, persistentState) job = Job() } override fun onDestroy() { super.onDestroy() job.cancel() } } Sevil Guler - 12.04.2019
  • 29. COROUTINE CANCELATION val job = launch { try { repeat(1000) { counter -> print(" $counter") delay(50L) } } catch (e: CancellationException) { print(" CancellationExceptionn") } } delay(1000L) job.cancel() job.join() Sevil Guler - 12.04.2019
  • 30. EXCEPTIONS ▸ An exception other than CancellationException in a coroutine scope cancels its parent.  ▸ CoroutineExceptionHandler  val handler = CoroutineExceptionHandler { _, exception -> println("Caught $exception") } ▸ If we want cancellation to be propagated only downwards we can use SupervisorJob or supervisorScope. Sevil Guler - 12.04.2019
  • 31. EXCEPTIONS fun main() = runBlocking { val handler = CoroutineExceptionHandler { _, exception -> println("Caught $exception with suppressed ${exception.suppressed.contentToString()}") } val job = GlobalScope.launch(handler) { launch { try { delay(Long.MAX_VALUE) } finally { throw ArithmeticException() } } launch { delay(100) throw IOException() } delay(Long.MAX_VALUE) } job.join() } Caught java.io.IOException with suppressed [java.lang.ArithmeticException] Sevil Guler - 12.04.2019
  • 32. EXCEPTIONS val supervisor = SupervisorJob() with(CoroutineScope(supervisor)) { val child1 = launch(handler) { println("Child1 is failing") throw AssertionError("child1 cancelled") } val child2 = launch { child1.join() println("Child1 cancelled: ${child1.isCancelled}") println("Child2 isActive: $isActive") try { delay(Long.MAX_VALUE) } finally { println("Finally Child2 isActive: $isActive") } } child1.join() println("Cancelling supervisor") supervisor.cancel() child2.join() } Child1 is failing Caught java.lang.AssertionError: child1 cancelled Cancelling supervisor Child1 cancelled: true Child2 isActive: true Finally Child2 isActive: false Sevil Guler - 12.04.2019
  • 33. WHAT IS NEXT? ▸ Channels ▸ Shared mutable state and concurrency ▸ Reactive streams with coroutines …. Sevil Guler - 12.04.2019