Skip to content

Instantly share code, notes, and snippets.

@ZakTaccardi
Created December 10, 2018 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZakTaccardi/a8cc5318121b135d3da7825a41ff981b to your computer and use it in GitHub Desktop.
Save ZakTaccardi/a8cc5318121b135d3da7825a41ff981b to your computer and use it in GitHub Desktop.
What is a coroutine?
// 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