Kotlin 生产者api可以';无法解决
我正在学习科特林合作计划。我遵循了一个教程,该教程使用此代码解释了协同程序的生产者-消费者api:Kotlin 生产者api可以';无法解决,kotlin,kotlin-coroutines,kotlinx.coroutines.channels,Kotlin,Kotlin Coroutines,Kotlinx.coroutines.channels,我正在学习科特林合作计划。我遵循了一个教程,该教程使用此代码解释了协同程序的生产者-消费者api: import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.launch import kotlinx.coroutines.channels.* fun produceNumbers() : ProducerJob<Int> =
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.channels.*
fun produceNumbers() : ProducerJob<Int> = produce {
for (x in 1..5) {
println("send $x")
channel.send(x)
}
}
我在我的智能IDE上尝试了这个代码。但我经常遇到编译器错误“Unresolved reference ProducerJob”和“Unresolved reference product”,这是为什么?您需要一个
CoroutineScope
在其中运行product
。也许你正在遵循一个相当过时的教程
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.produce
@ExperimentalCoroutinesApi
fun CoroutineScope.produceNumbers() = produce {
for (x in 1..5) {
println("send $x")
send(x)
}
}
你能显示你的依赖关系吗?用build.gradle更新了我的函数
ProducerJob
的返回类型是什么?它仍然无法解决。它现在也在新的API中消失了product
returnsReceiveChannel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.produce
@ExperimentalCoroutinesApi
fun CoroutineScope.produceNumbers() = produce {
for (x in 1..5) {
println("send $x")
send(x)
}
}