如何在 Kotlin 中等待任务完成

huangapple go评论75阅读模式
英文:

How to wait to finish task in kotlin

问题

internal fun handleResponse(items: List? = null) {
viewModelScope.launch(Dispatchers.IO) {
val isDataReturned = testItems != null
if (isDataReturned) {
dataModelList = getfilterDataList(items).toMutableStateList()
}
requestCompleteLiveData.postValue(isDataReturned)
}
}

我有一个像这样的函数

我通过API调用接收数据,所以它可能为空或空。在接收数据后,我将其传递给函数handleResponse以过滤数据。getfilterDataList()方法非常重,因为它具有大量数据,即来自服务器的超过1000个项目和子项目。

所以我考虑改进代码

  • 如果isDataReturned返回false,那么我将发送livedata。

  • 如果isDataReturned返回true,则我必须等待dataModelList收集所有值。

    var dataModelList = mutableStateListOf()

那么,实现这一目标的最佳方法是什么?

我可以分享给您我的getfilterDataList方法,但不是全部。

fun getfilterDataList(unfilteredList: List): MutableList {
return unfilteredList
.asSequence()
.mapNotNull { it.testData }
.filterNot { isInvalidTestData(it) }
.mapIndexed { index, testData ->
// 在这里添加更多代码
DataModel()
}.toMutableList()
}

英文:

I have a function like this

internal fun handleResponse(items: List<TestItem>? = null) {
    viewModelScope.launch(Dispatchers.IO) {
        val isDataReturned = testItems != null
        if (isDataReturned) {
            dataModelList = getfilterDataList(items).toMutableStateList()
        }
        requestCompleteLiveData.postValue(isDataReturned)
    }
}

I am receiving data through api call so it may be null or empty. After receiving the data I am passing in the function handleResponse to filter data. getfilterDataList() method is very heavy filter processing doing because it has huge data i.e. more than 1000 items and subitems coming from the server.

So I am thinking to improve code

  • if isDataReturned is return false then I'll send the livedata.

  • If isDataReturned is return true then I have to wait until all value collect by the dataModelList.

    var dataModelList = mutableStateListOf<DataModel>()
    

So what is the best way to achieve this?

I can share you my getfilterDataList method but not fully.

fun getfilterDataList(unfilteredList: List<TestItem>): MutableList<DataModel> {
        return unfilteredList
            .asSequence()
            .mapNotNull { it.testData }
            .filterNot { isInvalidTestData(it) }
            .mapIndexed { index, testData ->
                // more code in here
              DataModel()
            }.toMutableList()
}

答案1

得分: 1

你可以编写一个挂起函数,它会很简单,如下所示:

suspend fun handleResponse(items: List<String>? = null): List<String> {
    if (items.isNullOrEmpty()) {
        return listOf()
    }

    return withContext(Dispatchers.IO) {
        items.map { it + " MODIFIED" }
    }
}

现在你可以从协程或其他挂起函数中调用此函数来处理响应。

英文:

You can write suspend function which will be simple as:

suspend fun handleResponse(items: List&lt;String&gt;? = null): List&lt;String&gt; {
    if (items.isNullOrEmpty()) {
        return listOf()
    }

    return withContext(Dispatchers.IO) {
        items.map { it + &quot; MODIFIED&quot; }
    }
}

Now you can call this function from coroutine or from other suspend function to get handle response.

答案2

得分: 0

如果您想在使用Kotlin协程时等待任务完成。只需查看Async/Await的概念。通常在YouTube上可用。

在使用Async/Await时,您的协程将等待完成,然后执行接下来编写的代码。

这将解决您的问题。

英文:

If you want to wait for a task to complete while using kotlin coroutine. Simple have a look for the concept of Async/Await. Commonly available on YouTube.

While using Async/Await, your coroutine will wait to complete then execute further down written code.

This will solve your problem.

答案3

得分: 0

通过在Kotlin协程中使用runBlocking和await,您可以有效地暂停执行并等待特定任务或协程完成其执行。

英文:

By using runBlocking and await in Kotlin coroutines, you can effectively pause the execution and wait until a specific task or coroutine has finished its execution.

huangapple
  • 本文由 发表于 2023年6月15日 21:56:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定