https://kotlinlang.org logo
Title
u

ursus

01/22/2023, 8:55 PM
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
combine(myFlow, reEmitTrigger) { v, _ -> v)
val reEmitTrigger = MutableStateFlow(false)
reEmitTrigger.value = !reEmitTrigger.value
works but .. ugly
r

Rob

01/22/2023, 9:28 PM
Why would you need to re-emit?
u

ursus

01/22/2023, 9:30 PM
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
myFlow
.map { someMapper(it, clock.nowMillis() }
r

Rob

01/22/2023, 9:32 PM
Hmm. Maybe a
MutableStateFlow
that is updated every tick will work here?
u

ursus

01/22/2023, 9:34 PM
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

Rob

01/22/2023, 9:37 PM
Would this work for you?
u

ursus

01/22/2023, 9:38 PM
not really, what does that solve? it emits current time every 100ms
r

Rob

01/22/2023, 9:38 PM
I thought you wanted "time as flow".
u

ursus

01/22/2023, 9:39 PM
in theory yes, but every 100ms is wasteful I only "need" it to emit when some condition changes
r

Rob

01/22/2023, 9:41 PM
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

Stylianos Gakis

01/22/2023, 11:45 PM
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.
thingFlow.collect { myCondition ->
  val timeOfChange = System.currentTimeMillis()
  // use myCondition and the time of change.
}