Skip to content

Instantly share code, notes, and snippets.

@manoamaro
Created April 5, 2020 09:09
Show Gist options
  • Save manoamaro/c6ae7dda7c3194b010468c614f249b1a to your computer and use it in GitHub Desktop.
Save manoamaro/c6ae7dda7c3194b010468c614f249b1a to your computer and use it in GitHub Desktop.
// Using the GlobalScope just as an example.
// For Android, should use the lifecycle scope so everything is stopped according to the lifecycle
GlobalScope.launch(Dispatchers.Main) { // Where the non-blocking code will run - Main Thread
// "synchronous" call. All following code will run only when this blocks finish and return.
val result1 = withContext(Dispatchers.IO) {// where this code will run - IO specific pool of threads
// background thread
// blocking or cpu intensive work
// can return something
}
// Main Thread
// eg. update UI
// async code. This will run async and will not "block"
val asyncResult = async {
// background thread
// can return something
}
// Main Thread
// eg. update UI
// wait for the execution and get the result
val result2 = asyncResult.await()
// Main Thread
// eg. update UI
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment