Shalu TD
08/04/2021, 12:51 PMCLOVIS
08/04/2021, 12:57 PMCLOVIS
08/04/2021, 12:58 PMdammy_abayomi
08/04/2021, 1:03 PMmkrussel
08/04/2021, 1:08 PMlifecycleScope
and then the answer to the first question becomes no, and the others don't matter.Shalu TD
08/04/2021, 1:23 PMShalu TD
08/04/2021, 1:26 PMlifecycleScope
. The system itself cancel the coroutine if using the lifecycleScope
.I am asking do we need to cancel the coroutine if its not crashing while trying to update UI.ritesh
08/04/2021, 1:30 PMShalu TD
08/04/2021, 1:37 PMoverride fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
CoroutineScope(IO).launch {
val data = async { downloadData() }.await()
withContext(Main) {
findViewById<TextView>(R.id.textview).text = data.toString()
}
}
}
private suspend fun downloadData(): Int {
delay(10000)
return 40000
}
mkrussel
08/04/2021, 1:39 PMfindViewById
does after destruction. But it would be better to use lifecycleScope.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
lifecycleScope.launch {
val data = withContext(<http://Dispatcher.IO|Dispatcher.IO>) { downloadData() }
findViewById<TextView>(R.id.textview).text = data.toString()
}
}
private suspend fun downloadData(): Int {
delay(10000)
return 40000
}
mkrussel
08/04/2021, 1:41 PMwithContext(<http://Dispatchers.IO|Dispatchers.IO>)
should be in downloadData
.Shalu TD
08/04/2021, 1:44 PMShalu TD
08/04/2021, 1:45 PMmkrussel
08/04/2021, 1:45 PMmkrussel
08/04/2021, 1:48 PMfindViewById
could change with different API levels, so it might work now but not work in the future.Shalu TD
08/04/2021, 1:55 PM