【Android】在Activity中使用LifecycleScope替代GlobalScope

GlobalScope的问题

我们在Activity或Fragment中使用协程时,要尽量避免使用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是生命周期是process级别的,所以上面的例子中,即使Activity或Fragment已经被销毁,协程仍然在执行。

解决方法

使用androidx.lifecycle:lifecycle-runtime-ktx:2.2.0-alpha01或更高版本,会用LifecycleScope代替GlobalScope

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

参考 https://developer.android.com/topic/libraries/architecture/coroutines

你可能感兴趣的:(Kotlin,#,Kotlin,Coroutine,Android,android,安卓,LifecycleScope,CoroutineScope,Coroutine)