Producer api can't be resolved

323 views Asked by At

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?

1

There are 1 answers

2
Andrei Tanana On BEST ANSWER

You need a CoroutineScope to run produce in it. Maybe you are following a pretty outdated tutorial.

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