Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.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
重新使用封闭式Kotlin';s频道_Kotlin_Channel_Kotlin Coroutines_Flow - Fatal编程技术网

重新使用封闭式Kotlin';s频道

重新使用封闭式Kotlin';s频道,kotlin,channel,kotlin-coroutines,flow,Kotlin,Channel,Kotlin Coroutines,Flow,我想使用通道作为队列,但我需要定期清除它。我没有找到该频道的清除方法,我对频道进行了变通。取消并创建新的频道,但它看起来很糟糕 问题是: 我如何实现将Kotlin的通道用作带清理的队列?重新创建频道看起来不太好… 简化的上下文 我有一个外部系统调用的方法:enqueue(id:Int)和cancel(),我没有访问调用这些方法的系统的权限(在我的例子中是React原生方法) enqueue(id:Int)-将id排入队列进行处理(一次只能处理一个项目),如果之前没有启动,则开始处理队列 canc

我想使用通道作为队列,但我需要定期清除它。我没有找到该频道的
清除
方法,我对
频道进行了变通。取消
并创建新的
频道
,但它看起来很糟糕

问题是:

我如何实现将Kotlin的通道用作带清理的队列?重新创建频道看起来不太好…

简化的上下文

我有一个外部系统调用的方法:
enqueue(id:Int)
cancel()
,我没有访问调用这些方法的系统的权限(在我的例子中是React原生方法)

enqueue(id:Int)
-将
id
排入队列进行处理(一次只能处理一个项目),如果之前没有启动,则开始处理队列

cancel()
-取消挂起的处理,但允许完成当前处理项目的当前处理

My
Processor
是一个单例处理器,可以在取消(将项目添加到队列中)之前和之后(用于新处理)多次调用
排队(id:Int)

我的解决方案是将通道用作队列,并将其项作为流使用
cancel()
将取消允许当前项目processint完成的通道

问题是在channel.cancel()频道关闭后,我需要创建一个不太漂亮的新频道

fun main() = runBlocking<Unit> {
    val processor = Processor()
    repeat(3) { processor.enqueue(it) }
    delay(150)
    processor.cancelPending()
    delay(500)
    println("Run processing one more time.")
    repeat(3) { processor.enqueue(it) }
    delay(500)
}

class Processor : CoroutineScope by CoroutineScope(Dispatchers.Default) {
    private var channel = Channel<Int>(50)
    private var processJob: Job? = null

    fun enqueue(id: Int) {
        channel.offer(id)
        if (processJob?.isActive == true) return
        processJob = launch {
            channel.consumeAsFlow().collect { process(it) }
        }
    }

    private suspend fun process(id: Int) {
        delay(100)
        println("[$id] processed.")
    }

    fun cancelPending() {
        println("Cancel.")
        channel.cancel()
        channel = Channel(50)
    }
}
fun main()=运行阻塞{
val处理器=处理器()
重复(3){processor.enqueue(it)}
延迟(150)
processor.cancelPending()
延迟(500)
println(“再运行一次处理。”)
重复(3){processor.enqueue(it)}
延迟(500)
}
类处理器:CoroutineScope by CoroutineScope(Dispatchers.Default){
专用var通道=通道(50)
私有变量processJob:作业?=null
趣味排队(id:Int){
频道报价(id)
if(processJob?.isActive==true)返回
processJob=启动{
channel.consumeAsFlow().collect{process(it)}
}
}
私有挂起乐趣进程(id:Int){
延迟(100)
println(“[$id]已处理”)
}
有趣的等待(){
println(“取消”)
channel.cancel()
频道=频道(50)
}
}