https://kotlinlang.org logo
#flow
Title
# flow
s

Sudhir Singh Khanger

11/13/2020, 9:14 AM
Is there a flow operator that would let me loop through a list indefinitely? {1, 2, 3, 4} -> 1, 2, 3, 4, 1, 2, 3, and so on. I would then pass on these values to the UI using
LiveData
.
g

gildor

11/13/2020, 9:52 AM
If I understand you correctly, do you need something like this?
Copy code
flow {
   while(true) {
     yourList.forEach {
        emit(it)
      }
    }
}
e

ephemient

11/13/2020, 10:03 AM
would be more convenient if there were a
Copy code
suspend fun <T> FlowCollector<T>.emitAll(items: Iterable<T>)
overload built-in, but looks like it's only defined with
ReceiveChannel<T>
and
Flow<T>
parameters now
s

Sudhir Singh Khanger

11/13/2020, 10:04 AM
@gildor Ideally, it would be great to somehow cancel the while loop/flow once there are no observers observing the subject.
g

gildor

11/13/2020, 10:05 AM
Ideally, it would be great to somehow cancel the while loop/flow once there are no observers observing the subject
This how flow works by default, it’s a cold stream, start emitting when someone is collecting it, and will be cancelled if collection is cancelled (for this particular flow will be cancel on call of
emit
if flow is cancelled)
observing the subject
Subject?
e

ephemient

11/13/2020, 10:46 AM
also by default, the flow is run independently for each collector. hot shared/stateful flows are possible with `.shareIn()`/`.stateIn()`, but you don't want this to be a hot flow.
☝️ 1
s

Sudhir Singh Khanger

11/14/2020, 7:04 AM
Copy code
flow {
   while(true) {
     yourList.forEach {
        emit(it)
      }
    }
}
It seems like a while loop makes this a blocking call. No other code seems to execute except the while loop. Edit: If I add delay() within the forEach block then the rest of the code starts executing.
What I am trying to do is to have sliding image kind of thing. Currently, the list of image-urls are passed to the UI where in a loop these image-urls are passed to the image loading library. I was thinking if I could pass these urls from the repository to the UI on a regular interval in an efficient manner.
g

gildor

11/14/2020, 8:30 AM
emit is suspend function, it should allow other coroutines execute. Maybe you collector is blocking thread? Of course this flow emits a lot of values, but it's not blocking
Anyway, this what you need, it's efficient, but of course you should add delay, as operator or as part of flow if you need it