https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

andreasmattsson

09/01/2017, 8:31 AM
Hi! Cross-posting here from #kotlin-native : Any coroutine-gurus here than can help? I've wrapped a C-library method, that feeds values to a callback, in a kotlin method to capture the results (callback will be called multiple times) in a lambda. Basically called like this:
Copy code
library.invoke(arg) { value -> doSomething(value) }
Now what I'd like to do is wrap this somehow so that instead of using a callback my wrapping method returns a Sequence (going from a push to a pull style API). My first attempt was to use buildSequence:
Copy code
buildSequence { library.invoke(arg) { value -> yield(value) } }
But this gives
Suspension functions can be called only within coroutine body
. The Wrapping callbacks section in the documentation here looked promising: https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md#wrapping-callbacks But as far as I can tell this
suspendCoroutine
trick only works if the callback is called only once by the library. Mine is called many many times, and I want to have a sequence where I can consume items one by one and not have to gather them in a list first. Channels looks like a good approach but AFAIK they are only available in the
kotlinx.coroutines
package that does not work in Kotlin Native. Any suggestions? Are there any "out of the box" or idiomatic solutions for this that don't involve manually implementing a producer/consumer pattern using C/threading concurrency stuff?
g

gildor

09/01/2017, 8:51 AM
As I know there is no kotlin-native implementation of channels. The only way to write your own. Also, you can check coroutine implementation of sequences, there is an example in kotlinx.coroutines, it's simpler than channels. But there are plans to have kotlinx.coroutines for other platforms, not only jvm
a

andreasmattsson

09/01/2017, 9:05 AM
@gildor: Can you provide a GitHub link to that example? I'm having trouble finding it... 😕
g

gildor

09/01/2017, 9:14 AM
@andreasmattsson not sure now, I saw there generator example, can check later
a

andreasmattsson

09/01/2017, 9:15 AM
Thanks!
e

elizarov

09/01/2017, 10:33 AM
2 Views