如果您有类似的回调并且想知道它们何时触发,我为基本用例编写了以下代码。
它包装回调并跟踪其进度:
//Triggers a callback when all supplied callbacks have been called at least once
class CallbackLatch(
private val numberOfCallbacks: Int,
private val callback: () -> Unit
) {
private var autoIdCounter = 0
private val progress = mutableMapOf<Int, Int>()
fun <T> track(function: (input: T) -> Unit): (input: T) -> Unit {
val callbackId = autoIdCounter++
progress.putIfAbsent(callbackId, 0)
return {
function(it)
updateProgress(callbackId)
}
}
private fun updateProgress(id: Int) {
progress.apply {
this[id] = 1 + this.getOrElse(id) {0}
if (values.all { it > 0 } && values.size >= numberOfCallbacks) {
callback()
}
}
}
}
我想避免编写多个跟踪方法,例如:
fun <T> track(function: (input: T) -> Unit): (input: T) -> Unit
fun <T, U> track(function: (i1: T, i2: U) -> Unit): (i1: T, i2: U) -> Unit
fun <T, U ,V> track(function: (i1: T, i2: U, i3: V) -> Unit): (i1: T, i2: U, i3: V) -> Unit
是否可以,track方法的方法签名是什么? (很抱歉,如果重复的话,我找不到)