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


#1

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.


#2

Hope this helps:

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/-restricts-suspension/index.html


#3

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.


#4

Yes, I agree.

I suppose your proposal overlap the producer.

https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/produce.html

map/reduce operators are on the way…


#5

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{
  send(next())
}

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

it produces one element.


#6

My mistake. Should have done

produce {
            while(true) {
                sendBlocking(next())
            }
        }

#7

sendBlocking is not appropriate here, send is enought.


#8

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


#9

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


#10

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.