Last active
December 21, 2018 12:29
-
-
Save egorshustov/ff0469e2dff1aeead6a6aa5f31884426 to your computer and use it in GitHub Desktop.
Coroutines in UI example
This file contains hidden or 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
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() } |
This file contains hidden or 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
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