Is there a real way to recollect the `Flow` each x...
# flow
a
Is there a real way to recollect the
Flow
each x seconds? like:
Copy code
val flow = flow {
    emit(doApiCall())
}
.onEach{ delay(1000) }// something like that
........
flow.collect{
  //get flow value
}
I searched a lot but it seems that I need to put the code in fun and call it each time, what do you think?
e
is this what you want?
Copy code
flow {
    while (true) {
        emit(doApiCall())
        delay(1000)
    }
}
a
This works, but I look for an intermediate operator to apply on flow directly(like my example) because in some cases I receive a ready-flow(so there is no flow builder) from repo and pass it to the fragment.
e
in that case you can just wrap the flow in another,
Copy code
fun <T> Flow<T>.repeatWhen(suspend predicate: suspend FlowCollector<T>.() -> Boolean): Flow<T> = flow {
    do {
        yieldAll(this@repeatWhen)
    } while (predicate())
}
::doApiCall.asFlow()
    .repeatWhen {
        delay(1000)
        true
    }
a
I don't see
yieldAll()
fun in this scope, Although I tested
yield()
but didn't worked
e
my bad, it's
emitAll
a
Thanks it's working now, but I wonder if there is any negative side on performance by wrapping flows in general and in this case
d
wrt flow performance. Take a look at any of the stdlib flow operators and builders. They all work like this, creating new flows and sometimes new coroutines to wrap inbound flows. That is intentionally side-stepping your performance question, turning it from a absolute to a relative statement. Doing as @ephemient does or similar should be equivilent performance to any stdlib flow operator.
e
with a caveat:
channelFlow
involves more overhead than `kotlinx.coroutines.flow.internal.flowScope`/`.scopedFlow`