无法在ViewModel中调用协程作用域函数

时间:2019-12-25 00:03:14

标签: android kotlin-coroutines android-viewmodel

这是我的BaseViewModel

abstract class BaseViewModel : ViewModel(), CoroutineScope {

    private val parentJob = SupervisorJob()

    override val coroutineContext: CoroutineContext
        get() = parentJob + Dispatchers.Main

    override fun onCleared() {
        super.onCleared()
        parentJob.cancel()
    }
}

然后我有LevelFragment,其中LevelViewModel是继承的BaseViewModel。在LevelViewModel中,我具有fun load() = launch {}函数。

我正在尝试使用LevelFragment显示多个ViewPager。因此,我创建了PagerAdapter并继承了FragmentStatePagerAdapter。文档中关于FragmentStatePagerAdapter的内容是When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment。我不确定viewModel是否是保存状态的一部分,但是当我转到销毁的片段并重新创建该片段时,我无法调用load()函数,它不是编译错误或运行时崩溃,但是当我尝试在不被调用的函数中放置一个断点。我仍然可以调用没有协程作用域的另一个函数。

此外,我已经尝试使用viewModelScope,结果仍然相同。

是否还有其他人也遇到了这些问题,或者您是否知道可能是什么原因造成的?

0 个答案:

没有答案