Home > Enterprise >  How to emit latest value with delay from faster original flow?
How to emit latest value with delay from faster original flow?

Time:12-17

I have 2 flows. First flow updates every 50ms. I have the second flow which is equal to first flow but i want it to produce latest value from original flow every 300ms. I found debounce extension for flows but it doesn't work (note from docs):

Note that the resulting flow does not emit anything as long as the original flow emits items faster than every timeoutMillis milliseconds.

So when i'm trying to emit value each 300 ms with debounce it doesn't emit at all because original flow is faster than i need. So how can i make something like that:

  1. delay 300ms
  2. check original flow for latest value
  3. emit this value
  4. repeat

my flows right now:

// fast flow (50ms)
val orientationFlow = merge(_orientationFlow, locationFlow)

val cameraBearingFlow = orientationFlow.debounce(300ms)

P.S. this approach doesn't fit because we are delaying value so it's not fresh after 300ms. I need to get the freshest value after 300ms:

val cameraBearingFlow = azimuthFlow.onEach { 
        delay(ORIENTATION_UPDATE_DELAY)
        it
    }

CodePudding user response:

You need sample instead of denounce

val f = fastFlow.sample(300)
  • Related