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

Paul Woitaschek

11/26/2018, 9:30 AM
I have this function where I'm counting down dates. Now line 5 is suspending. The compiler warns me that it can only be called from within a coroutine body
d

diesieben07

11/26/2018, 10:29 AM
I think you want to use channels in this case:
Copy code
fun main(args: Array<String>) {
    runBlocking {
        produceDates()
            .mapNotNull { it /* something suspending */ }
            .firstOrNull()
    }
}

fun CoroutineScope.produceDates(): ReceiveChannel<LocalDate> = produce {
    generateSequence(LocalDate.now()) { it.minusDays(1) }
        .take(10)
        .forEach { send(it) }
}
But something better seems to be planned: https://github.com/Kotlin/kotlinx.coroutines/issues/254
g

gildor

11/26/2018, 1:26 PM
Sequences is completely syncronous API, so run blocking is the only option.
Channels is async sequence of events in kotlinx.coroutines, but big difference: channel is hot stream, so next event computed before it consumed, so as Take already mentioned, real solution is cold streams abstraction
p

Paul Woitaschek

11/26/2018, 3:39 PM
Is there any progress on that issue? It seems that it's top priority (DontUseThisAnnotations everywhere) but I can't find any commits tackling that issue.
b

bdawg.io

11/26/2018, 5:04 PM
It's just marked experimental because it is going to change
g

gildor

11/27/2018, 1:52 AM
It seems that it’s top priority (DontUseThisAnnotations everywhere
this is not related to cold streams directly. Channels will be there even after cold streams release. This is just means that API of channels experimental, may be changed, so you have to use annotations or enable it for your project explictly
4 Views