How do I make a state flow that: - emits its value...
# coroutines
r
How do I make a state flow that: • emits its value immediately every time it changes • emits its value periodically X seconds after it changes (and keeps doing it until it changes) • don’t emit anything when the value is null (if it’s changed to null and periodically) I know how to make a flow that basically combines the origin state flow with an independent periodic flow re-emitting the value of the state flow, but it’s not exactly what I want. I found no simple way to make a timer either
j
I'm curious, could you please explain your use case for re-emitting the same value over and over?
👀 1
m
sth like?
Copy code
val trigger = MutableSharedFlow<Sth>()
val flow = trigger.
.flatMapLatest {
   if(it!=null)
   while(true){
      emit(it)
      delay(1000)
   }
   }
}
writing from memory, I might be completely wrong
e
close. flatMap needs another Flow, you probably meant that wrapped in a flow builder or
Copy code
trigger.transformLatest { item ->
    emit(item)
    if (item != null) {
        delay(Duration.seconds(1))
        emit(item)
    }
}
the mention of "state flow" is confusing, though. a state flow conflates equals values; if you want something that re-emits the same value, it can't be a StateFlow.
1
j
+1 for "state flow" and identical value emissions.. I don't get it either, hence my question about the use case here
m
Yeah, both points are valid :)
As for the use case - can't speak for op, but I implemented something a bit similar (although in rxjava) for a heartbeat animation which was based on actual user's heartbeat rate.
a
Seems like the bullet points listed are jobs for flows and not necessarily state flow
l
You most likely want a custom operator for regular `Flow`s or `SharedFlow`s that emits periodically over and over. It could use
transformLatest
.
r
The state flow was basically the primary source of data, not the output of what I wanted. I needed something like that because that data was then converted and mixed with some other data that may or may have not changed (like, the current time) to produce a result, hence why I wanted to re-emit the same thing at the beginning of the flow, resulting in potential actual change later
I did something less clever in the end. It’ll probably trigger more requests and updates than necessary but it’s not really worth to look for a better option