我的应用程序中有一个类似于以下的代码
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)
在生产中,我得到很多NPEs的doSomething(),而访问context。
我的假设是coroutine调用cancel()in后被取消onDestroy(),所以我没有费心检查context空值。但看起来continues即使在cancel()被调用之后也能执行。我认为这会发生,如果cancel()在完成后调用withContext和恢复之前coroutines。
所以我替换doSomething()了以下内容。
private fun doSomething() = launch …Run Code Online (Sandbox Code Playgroud)