Kotlin Coroutines - Suspend Function Returning A Flow Runs Forever
I am making a network repository that supports multiple data retrieval configs, therefore I want to separate those configs' logic into functions. However, I have a config that fetc
Solution 1:
I am not sure whether this is a solution to your problem, but you do not need to have a suspending function that returns a Flow. The lambda you are passing is a suspending function itself:
fun<T>flow(block: suspendFlowCollector<T>.() -> Unit): Flow<T> (source)
Here is an example of a flow that repeats a (GraphQl) query (simplified - without type parameters) I am using:
overridefunquery(query: Query,
updateIntervalMillis: Long): Flow<Result<T>> {
return flow {
// this ensures at least one queryval result: Result<T> = execute(query)
emit(result)
while (coroutineContext[Job]?.isActive == true && updateIntervalMillis > 0) {
delay(updateIntervalMillis)
val otherResult: Result<T> = execute(query)
emit(otherResult)
}
}
}
Solution 2:
I'm not that good at Flow but I think the problem is that you are delaying only the getData() flow instead of delaying both of them. Try adding this:
suspendfungetData(config: MyConfig): Flow<List<Data>>
{
return flow {
when (config)
{
CONTINUOUS ->
{
fetchContinuously().collect { updatedList ->
emit(updatedList)
delay(refreshIntervalInMs)
}
}
}
}
}
Take note of the delay(refreshIntervalInMs)
.
Post a Comment for "Kotlin Coroutines - Suspend Function Returning A Flow Runs Forever"