小编ada*_*sha的帖子

关于 Kotlin 协程取消的问题

我的应用程序中有一个类似于以下的代码

class MyFragment : Fragment(), CoroutineScope by MainScope() {

    override fun onDestroy() {
        cancel()
        super.onDestroy()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        doSomething()
    }

    private fun doSomething() = launch {
        val data = withContext(Dispathers.IO) {
            getData()
        }

        val pref = context!!.getSharedPreferences("mypref", MODE_PRIVATE)
        pref.edit().putBoolean("done", true).apply()
    }
}
Run Code Online (Sandbox Code Playgroud)

在生产中,我得到很多NPEsdoSomething(),而访问context

我的假设是coroutine调用cancel()in后被取消onDestroy(),所以我没有费心检查context空值。但看起来continues即使在cancel()被调用之后也能执行。我认为这会发生,如果cancel()在完成后调用withContext和恢复之前coroutines

所以我替换doSomething()了以下内容。

    private fun doSomething() = launch …
Run Code Online (Sandbox Code Playgroud)

android coroutine kotlin

3
推荐指数
1
解决办法
2147
查看次数

标签 统计

android ×1

coroutine ×1

kotlin ×1