Skip to content

Instantly share code, notes, and snippets.

@egorshustov
Last active December 21, 2018 12:29
Show Gist options
  • Save egorshustov/ff0469e2dff1aeead6a6aa5f31884426 to your computer and use it in GitHub Desktop.
Save egorshustov/ff0469e2dff1aeead6a6aa5f31884426 to your computer and use it in GitHub Desktop.
Coroutines in UI example
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
progress_auth.visibility = View.VISIBLE
button_auth.setOnClickListener {
val actionBar = supportActionBar
GlobalScope.launch(Dispatchers.Main) {
// testAsync() doesn't block UI, returns Deferred<String>
val newTitle = testAsync()
// Let's get String from Deferred<String>:
actionBar?.title = newTitle.await()
}
}
}
private fun waitAndReturnNewTitle(): String {
Thread.sleep(5000)
return "new_title"
}
private fun testAsync() = GlobalScope.async(Dispatchers.Default) { waitAndReturnNewTitle() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
progress_auth.visibility = View.VISIBLE
button_auth.setOnClickListener {
val actionBar = supportActionBar
GlobalScope.launch(Dispatchers.Main) {
// testAsync() doesn't block UI, returns String
val newTitle = testAsync()
actionBar?.title = newTitle
}
}
}
private fun waitAndReturnNewTitle(): String {
Thread.sleep(5000)
return "new_title"
}
private suspend fun testAsync(): String = withContext(Dispatchers.Default) { waitAndReturnNewTitle() }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment