Rollie
Rollie

Reputation: 4752

Is there a way to have a producer member function?

Using coroutines 1.3-RC2, I want to do the following:

class Foo {
    fun getPrimes() = produce {
        var i = 0
        while (true) {
            if (i.isPrime()) {
                send(i)
            }

            i++
        }
    }
}

But it complains that produce can't be used due to receiver mismatch. I could wrap produce{} in runBlocking, and it compiles, but it blocks.

So, how to achieve this producer pattern, such that client code can run myFoo.getPrimes().consumeEach(...)?

Upvotes: 1

Views: 65

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8442

produce requires a coroutine scope to run in. You can pass a scope:

class Foo {
    fun getPrimes(scope: CoroutineScope) = scope.produce {
        var i = 0
        while (true) {
            if (i.isPrime()) {
                send(i)
            }

            i++
        }
    }
}

or, for example, mark getPrimes suspend and create a new scope:

class Foo {
    suspend fun getPrimes() = coroutineScope {
        produce {
            var i = 0
            while (true) {
                if (i.isPrime()) {
                    send(i)
                }

                i++
            }
        }
    }
}

Upvotes: 1

Related Questions