Is there a way to use actual suspended function in `buildSequence`?


As buildSequence accepts suspended function as argument, I would expect something like this to work:

buildSequence {
    yield( next())

Here next is suspended function defined somewhere else. But compiler gives error about restricted coroutine scope. I do not fully understand, what does this message means so I wander if it is possible to actually use suspended function in this block. Of course, I can always wrap it in runBlocking, but in this case, I do not see any reason to make internal function suspended.
In all of the examples I have encountered, buildSequence never uses suspended code.


Hope this helps:


So, correct me if I am wrong, buildSequence does not actually support coroutines and uses suspended notation only to add some syntactic sugar to yield. At least that is what I understood, since the whole concept is rather hard to understand at once.
But it still makes sense to add possibility for lazy sequences with actual suspended producers.


Yes, I agree.

I suppose your proposal overlap the producer.

map/reduce operators are on the way…


Tried it just now, and it does not work as expected. The problem is that ReceiveChannel relies a lot on consumeEach method. This methods consumes only those values which are already in the channel. If I am doing something like:

val channel = produce{

channel.takeWhile { ... }.toList()

it produces one element.


My mistake. Should have done

produce {
            while(true) {


sendBlocking is not appropriate here, send is enought.


suspendingSequence seems to be very interesting but its only available on examples module. Is there any reason to be only there?


Channels in kotlinx.coroutines represent the same concept, but more elaborate.


Currently there are at least three entities with similar functionality: Java Streams, Sequences and Channels. It is a source of some confusion. I understand that current kotlin type system does not allow to replace Channel calls with suspended functions with Sequence calls with regular functions, but there could be a situation, when you want to use suspended function in sequence manipulation and vice versa.