小编杨梦榕*_*杨梦榕的帖子

Kotlin CoroutineScope 无法在 android 视图中取消

例如,这个视图。当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)

android coroutine kotlin kotlin-coroutines

5
推荐指数
1
解决办法
3428
查看次数

标签 统计

android ×1

coroutine ×1

kotlin ×1

kotlin-coroutines ×1