Problems with GlobalScope
When we use coroutines in Activity or Fragment, we should try to avoid using them GlobalScope
.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
GlobalScope.launch {
val data = withContext(Dispatchers.IO) {
loadData()
}
initUi(data)
}
}
...
}
GlobalScope
The life cycle is at the process level, so in the above example, even if the Activity or Fragment has been destroyed, the coroutine is still executing.
Solution
Use androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01
or higher version, will use LifecycleScope
insteadGlobalScope
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
lifecycleScope.launch {
val data = withContext(Dispatchers.IO) {
loadData()
}
initUi(data)
}
}
...
}
class MyFragment: Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewLifecycleOwner.lifecycleScope.launch {
val data = withContext(Dispatchers.IO) {
loadData()
}
initUi(data)
}
}
...
}
Refer to https://developer.android.com/topic/libraries/architecture/coroutines