首页 > 解决方案 > 调用 viewModelScope 仅在第一次调用时执行

问题描述

我有一个执行 api 调用的 ViewModel 方法。由于某种原因,我只能执行一次。

class MyViewModel : ViewModel() {

    fun apiCall() {

        // Function call gets here every time.
        // viewModelScope is not active on subsequent calls

        viewModelScope.launch {

            // Only gets inside here the first call

            executeApiCall()

        }
    }

    suspend fun executeApiCall() = withContext(Dispatchers.Default) {
        // Only gets inider here the first call
    }

它每次都清楚地进入“apiCall()”函数,但无法使用 viewModelScope 执行作业。

我认为这与我的 viewModelScope 对后续调用不活跃有关,但我不确定我必须做什么才能使其再次活跃。作为冰雹结婚,也尝试使用不同的调度程序。

标签: androidkotlinkotlin-coroutines

解决方案


推荐阅读