Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/219.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 为什么在协同outineScope中的lambda中的挂起函数调用会产生错误?_Android_Kotlin Coroutines - Fatal编程技术网

Android 为什么在协同outineScope中的lambda中的挂起函数调用会产生错误?

Android 为什么在协同outineScope中的lambda中的挂起函数调用会产生错误?,android,kotlin-coroutines,Android,Kotlin Coroutines,我有一个重试策略,它接收lambda,启动一个CoroutineScope,增加一个重试计数器,检查是否达到最大重试次数,根据重试计数计算waitTime,延迟此时间的作用域,最后调用lambda: fun connectionRetryPolicy(block: () -> Unit) { Timber.d("connectionRetryPolicy: called") // Launch the coroutine

我有一个重试策略,它接收lambda,启动一个
CoroutineScope
,增加一个重试计数器,检查是否达到最大重试次数,根据重试计数计算
waitTime
,延迟此时间的作用域,最后调用lambda:

        fun connectionRetryPolicy(block: () -> Unit) {

            Timber.d("connectionRetryPolicy: called")

            // Launch the coroutine to wait for a specific delay
            val scope = CoroutineScope(Job() + Dispatchers.Main)
            scope.launch {

                // Get and increment the current retry counter
                val counter = retryCounter.getAndIncrement()

                // Check if the counter is smaller than the maximum retry count and if so, wait a bit and execute the given function
                if (counter < maxRetry) {

                    // Calculate the time to be waited
                    val waitTime: Long = (2f.pow(counter) * baseDelayMillis).toLong()

                    // Delay the scope for the calculated time
                    delay(waitTime)

                    // Execute the given function
                    block()

                }

                // Else, throw an exception
                else {

                    throw FirebaseNetworkException("Retry count reached")

                }

            }

        }

现在,林特告诉我,
connecttologleplaybillingservice
不能在lambda内部调用,因为它是一个挂起函数,需要在
CoroutineScope
内部调用。正如您所看到的,我在
connectionRetryPolicy
中调用
CoroutineScope
中的lambda

这是棉绒里的虫子还是我做错了什么?我知道,我可以在lambda中创建一个新的
CoroutineScope
,然后调用
connecttoogleplaybillingservice
,我不确定这在性能方面是否明智。

替换

fun connectionRetryPolicy(block: () -> Unit)


因为您的
block()
将在一个协同程序中运行,但另一个方法不知道这一点。

哦,我的天啊,现在我觉得自己很笨。实际上我已经试过了,但是在
挂起
之后添加了
乐趣
。好的,非常感谢你的快速回答!
fun connectionRetryPolicy(block: () -> Unit)
fun connectionRetryPolicy(block: suspend () -> Unit)