取消suspendCancellableCoroutine中的回调

问题描述

我已经在callbackCancellableCoroutine中包装了一个回调,以将其转换为悬挂函数:

suspend fun TextToSpeech.speakAndWait(text: String) : Boolean {
    val uniqueUtteranceId = getUniqueUtteranceId(text)
    speak(text,TextToSpeech.QUEUE_FLUSH,null,uniqueUtteranceId)
    return suspendCancellableCoroutine { continuation ->
        this.setOnUtteranceProgressListener(object : JeLisUtteranceProgressListener() {
            override fun onDone(utteranceId: String?) {
                if(utteranceId == uniqueUtteranceId) {
                    Timber.d("word is read,resuming with the next word")
                    continuation.resume(true)
                }
            }
        })
    }
}

我用片段的 lifecycleScope协程作用域调用此函数,并且我假设当片段被破坏时它被取消了。但是,LeakCanary报告说,由于此侦听器,我的片段正在泄漏,并且我用日志验证了即使取消了协程,回调仍被调用。

因此,似乎用suspendCancellableCoroutine(而不是suspendCoroutine)包装不足以取消回调。我想我应该积极检查工作是否活跃,但是如何?我尝试了coroutineContext.ensureActive()并在回调中检查了coroutineContext.isActive,但是IDE给出了一个错误,指出“只能在协程体内调用悬浮函数” 我还能做些什么来确保如果取消工作,它不会恢复吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)