Is there a elegant way to reemit the last value of...
# coroutines
u
Is there a elegant way to reemit the last value of a flow when same some other signal happens? currently I have a mutable state flow where I emit a negation (to be unique) so
combine
reemits
Copy code
combine(myFlow, reEmitTrigger) { v, _ -> v)
Copy code
val reEmitTrigger = MutableStateFlow(false)
Copy code
reEmitTrigger.value = !reEmitTrigger.value
works but .. ugly
r
Why would you need to re-emit?
u
In my case I need time as a flow, but obviously I dont want to emit every nanosecond, so I have this workaround to "pull" current time instead, but to "refresh" it I need to reemit the last value, so it then gets mapped with the current time
Copy code
myFlow
.map { someMapper(it, clock.nowMillis() }
r
Hmm. Maybe a
MutableStateFlow
that is updated every tick will work here?
u
I had that but I'd rather have the time at mapping time, if I pop it into a stateflow, it wont get combined with
myFlow
in a instant, there is some delay
r
Would this work for you?
u
not really, what does that solve? it emits current time every 100ms
r
I thought you wanted "time as flow".
u
in theory yes, but every 100ms is wasteful I only "need" it to emit when some condition changes
r
Would this work for you?
Maybe this too. Otherwise I need more context.
As far I know there is no RxJava
sample
operator for kotlin flows.
Flows can emit the same value twice like in this example.
s
I only “need” it to emit when some condition changes
Then collect that “condition” changes, and at the collection do a System.currentTimeMillis() to see the time which that change happened.
Copy code
thingFlow.collect { myCondition ->
  val timeOfChange = System.currentTimeMillis()
  // use myCondition and the time of change.
}
168 Views