例如,这个视图。当onDetachedFromWindow调用范围被取消时,但启动的作业仍然处于活动状态。
class TestView : FrameLayout,CoroutineScope {
val TAG = "TestView"
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + Job()
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
launch {
while (true) {
Log.i(TAG,"is in launch coroutine....${coroutineContext} ${this@TestView.coroutineContext}")
delay(1000)
}
}
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
cancel()
Log.i(TAG,"onDetachedFromWindow")
}
}
Run Code Online (Sandbox Code Playgroud)
日志是
2019-09-19 21:32:26.652 22912-22912/com.ymr.myapplication I/TestView: is in launch coroutine....[StandaloneCoroutine{Active}@7f9d20f, Main] [JobImpl{Active}@2f3fde2, Main] …Run Code Online (Sandbox Code Playgroud)