Skip to content

Instantly share code, notes, and snippets.

@binaryroot
Created September 4, 2018 22:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save binaryroot/18eb265b6bc73c89f02279e39171ed63 to your computer and use it in GitHub Desktop.
Save binaryroot/18eb265b6bc73c89f02279e39171ed63 to your computer and use it in GitHub Desktop.
How coroutines switch back to the main thread.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
launch(context = UI) {
val result = async { loadString() }.await()
Log.d("TAG",
"Post execution thread:"+Thread.currentThread().name)
textView.text = result
}
}
private suspend fun loadString() : String {
Log.d("TAG", "Execution thread: "+Thread.currentThread().name)
delay(1000L)
return "Some loaded string..."
}
}
@david-ortegon-meli
Copy link

Which version of coroutines did you use to have the launch method in the Activity?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment