Created
December 10, 2018 20:29
-
-
Save ZakTaccardi/a8cc5318121b135d3da7825a41ff981b to your computer and use it in GitHub Desktop.
What is a coroutine?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1 | |
Thread { | |
var counter = 0 | |
counter++ | |
counter++ | |
println("$counter") // will always print "2" | |
} | |
// 2 | |
// for every Request, a Response is returned | |
fun handleRequest(request: Response): Reponse | |
// (caption) A `Response` is guaranteed to be returned on the same thread that `handleRequest(request)` was invoked on. | |
// 3 | |
fun handleRequest(request: Response): Reponse { | |
val userId = request.userId | |
// request thread is blocked while network call is made | |
val networkData = network.loadData(userId) | |
return networkData.asResponse() | |
} | |
// 4 | |
scope.launch { | |
var functionsCalled: Int = 0 // mutable shared state | |
withContext(Dispatchers.IO) { // switch to an IO thread | |
val profile = database.loadUserProfile(userId) // suspension point | |
functionsCalled++ | |
withContext(Dispatchers.UI) { // switch to the UI thread | |
ui.show(profile) | |
functionsCalled++ | |
} | |
} | |
println(functionsCalled) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment