gpt4 book ai didi

android - 等待我的代码完成使用Kotlin从API调用中获取所有信息

转载 作者:行者123 更新时间:2023-12-02 13:33:52 25 4
gpt4 key购买 nike

嗨,我是Kotlin的新手

我正在尝试编写以下代码-

private fun syncLocalCartItemsToNetwork(tokenObject: MyVerteUserAuthTokenObject) {
val failedSyncedProducts: MutableList<String> = mutableListOf()


locallySavedCartModels.forEach { //I need to make the code wait until all callbacks from this loop finishes
ShoppingCartUtils.addItemToCart(tokenObject.token, it, this@ShoppingCartActivity, object : ShoppingCartUtils.OnMyVerteCartProductsSyncListener {
override fun onProductSyncFailed(productID: String) {
failedSyncedProducts.add(productID)
}
})
}

if (failedSyncedProducts.isNotEmpty()) {
val builder = AlertDialog.Builder(this)
builder.setTitle("Shopping Cart was not fully synced")
builder.setMessage("The following items were not synced well due to stock availability, please re add them - \n\n" +
"${failedSyncedProducts.forEach { it + "\n\n" }}")
builder.setPositiveButton("Confirm") { dialog, _ ->
dialog.dismiss()
}
val dialog: AlertDialog = builder.create()
dialog.show()
}
Toast.makeText(this@ShoppingCartActivity, "finished", Toast.LENGTH_SHORT).show()


}

如您所见,我正在遍历所有 locallySavedCartModels并可能从中获得结果。

我需要的选项是使功能等待,直到所有回调都从forEach循环中完成,然后才继续执行我的代码以检查我的String列表是否为空。

如何使用Kotlin做到这一点?

最佳答案

使用协程可能是最干净的方法,但这意味着重写ShoppingCartUtils以使用暂停函数而不是回调。

要使用现有的代码,一种方法可能是创建一个类,该类在被调用足够多的时间后执行剩余的代码,如下所示:

class CallbackAggregator(val count: Int) {
var finalCallback: (() -> Unit)? = null
private var calls = 0

fun increment() {
if (++calls == count)
finalCallback?.invoke()
}
}

用法:
private fun syncLocalCartItemsToNetwork(tokenObject: MyVerteUserAuthTokenObject) {
val failedSyncedProducts: MutableList<String> = mutableListOf()

val aggregator = CallbackAggregator(locallySavedCartModels.size)

locallySavedCartModels.forEach {
ShoppingCartUtils.addItemToCart(tokenObject.token, it, this@ShoppingCartActivity, object : ShoppingCartUtils.OnMyVerteCartProductsSyncListener {
override fun onProductSyncFailed(productID: String) {
failedSyncedProducts.add(productID)
aggregator.increment()
}
})
}

aggregator.finalCallback = {
if (failedSyncedProducts.isNotEmpty()) {
AlertDialog.Builder(this@ShoppingCartActivity).apply {
title = "Shopping Cart was not fully synced"
message = "The following items were not synced well due to stock availability, please re add them - \n\n" +
"${failedSyncedProducts.joinToString("\n\n")}")
setPositiveButton("Confirm") { dialog, _ ->
dialog.dismiss()
}
create().show()
}
}
Toast.makeText(this@ShoppingCartActivity, "finished", Toast.LENGTH_SHORT).show()
}
}

关于android - 等待我的代码完成使用Kotlin从API调用中获取所有信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59842038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com