0

I am learning Kotlin coroutines. I followed a tutorial which uses this code to explain the producer consumer api of coroutines:

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)
    }
}

My build.gradle :

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.3.41'
}

group 'com.mm'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.1.1"
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

I tried the code on my Intellij IDE. But I constantly get compiler error "Unresolved reference ProducerJob" and "Unresolved reference produce", why is that?

4

1 回答 1

0

你需要一个CoroutineScope在其中运行produce。也许您正在关注一个非常过时的教程。

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)
    }
}
于 2019-09-04T09:35:10.283 回答