相关疑难解决方法(0)

Kotlin 协程 - 返回 Flow 的挂起函数永远运行

我正在制作一个支持多个数据检索配置的网络存储库,因此我想将这些配置的逻辑分离为函数。

但是,我有一个配置,可以按指定的时间间隔连续获取数据。当我将这些值发送到原始流程时,一切都很好。但是,当我将逻辑放入另一个函数并通过它返回另一个流时,它不再关心其协程范围。即使范围取消后,它仍会继续获取数据。

TLDR:当使用 currentCoroutineContext 来控制循环的终止时,返回流的挂起函数将永远运行。

我在这里做错了什么?这是我的代码的简化版本:

调用 viewmodels 函数的片段基本上调用 getData()

 lifecycleScope.launch {
            viewModel.getLatestDataList()
        }
Run Code Online (Sandbox Code Playgroud)

存储库

suspend fun getData(config: MyConfig): Flow<List<Data>>
{
    return flow {

        when (config)
        {
            CONTINUOUS ->
            {
                //It worked fine when fetchContinuously was ingrained to here and emitted directly to the current flow
                //And now it keeps on running eternally
                fetchContinuously().collect { updatedList ->
                    emit(updatedList)
                }
            }
        }
    }
}


//Note logic of this function is greatly reduced to keep the focus on the problem
private …
Run Code Online (Sandbox Code Playgroud)

multithreading android kotlin kotlin-coroutines

6
推荐指数
1
解决办法
2万
查看次数