[Android] Use LifecycleScope instead of GlobalScope in Activity

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)
        }
    }
    ...
}

GlobalScopeThe 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-alpha01or higher version, will use LifecycleScopeinsteadGlobalScope

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

Guess you like

Origin blog.csdn.net/vitaviva/article/details/108897278
Recommended