https://kotlinlang.org logo
Title
m

Mark

11/01/2018, 2:10 AM
Hi - I’m experimenting with
sequence {}
but getting “Restricted suspending functions can only invoke member or extension suspending functions on their restricted coroutine scope”. I can’t seem to find any information about this. Any pointers please? https://pl.kotl.in/B1hRgy_2m Presumably I need to use a suspending extension function of CoroutineScope?
g

gildor

11/01/2018, 2:35 AM
because sequence is completely synchronous, you cannot use any arbitrary suspending functions there, only synchronous yield
m

Mark

11/01/2018, 2:38 AM
Ok thanks. I was thinking/hoping it was just some kind of channel where the provider is lazily creating/sending items in the background and the receiver is picking up the items as it needs them
g

gildor

11/01/2018, 2:39 AM
If it would work like that
toList()
would be lock the thread and it doesn’t sound as a good idea
instead you can use Channels
m

Mark

11/01/2018, 2:39 AM
Yeah, the toList() was just playing around in case the compiler worked out that the sequence was never accessed
g

gildor

11/01/2018, 2:40 AM
any operation on such sequence would be block thread, not only toList()
m

Mark

11/01/2018, 2:42 AM
Okay, but a launch/async would deal with that
g

gildor

11/01/2018, 2:42 AM
to provide fully asynchronous sequences, all sequence operators also should be suspending to avoid problem with blocking And we have such API already it called
Channels
m

Mark

11/01/2018, 2:43 AM
Okay, so I guess
sequence{}
is only useful for when calculating the next item is reasonably fast (i.e. non IO-blocking)?
g

gildor

11/01/2018, 2:44 AM
Yes, sequences are completely synchronous
m

Mark

11/01/2018, 2:46 AM
Thanks for that. And with the default buffer, that would suspend so that items are only calculated when required?
g

gildor

11/01/2018, 2:48 AM
by default produce uses Rendezvous channel
m

Mark

11/01/2018, 2:49 AM
Ok, thanks Andrey, I’ll dive into that
g

gildor

11/01/2018, 2:50 AM
and yeah, with Rendezvous channel
send
will suspend until someone consumes this value
👍 1
m

Mark

11/01/2018, 2:52 AM
It suspends before calculating the next value or after?
g

gildor

11/01/2018, 2:52 AM
when you call
send
so value should be calculated before this
m

Mark

11/01/2018, 2:52 AM
Right, so it’s kind of got it there ready for the next consumption
g

gildor

11/01/2018, 2:52 AM
channels are “hot”
👍 2
There is a plan to provide also “cold” streams, which calculate values on request https://github.com/Kotlin/kotlinx.coroutines/issues/254
actually this issue has many good explanations directly related to your original question
👍 1