Browse Source

more intuitive .asTimedFlow extension

main
James Fenn 2 months ago
parent
commit
655813d8f7
3 changed files with 17 additions and 16 deletions
  1. +2
    -2
      audio-automation/src/me/jfenn/audio/utils/Metronome.kt
  2. +12
    -12
      audio-automation/src/me/jfenn/audio/utils/TimedFlow.kt
  3. +3
    -2
      audio-automation/src/me/jfenn/audio/utils/extensions/TimedFlow.kt

+ 2
- 2
audio-automation/src/me/jfenn/audio/utils/Metronome.kt View File

@@ -14,14 +14,14 @@ class Metronome(

private var isRunning = true

val onTick: TimedFlow<Int> = TimedFlow(flow {
val onTick: TimedFlow<Int> = flow {
var i = ((System.currentTimeMillis() - manager.startTime) / interval).toInt() + 1
while (isRunning) {
val nextTime = manager.startTime + (interval * i)
delay(nextTime - System.currentTimeMillis())
if (isRunning) emit(TimedInfo(i++, nextTime))
}
}.shareIn(manager.scope, SharingStarted.Lazily))
}.shareIn(manager.scope, SharingStarted.Lazily).asTimedFlow()

fun stop() {
isRunning = false


+ 12
- 12
audio-automation/src/me/jfenn/audio/utils/TimedFlow.kt View File

@@ -12,25 +12,23 @@ class TimedFlow<T>(
@OptIn(ExperimentalTypeInference::class)
inline fun <R> transform(
@BuilderInference crossinline action: suspend TimedFlowCollector<R>.(value: T) -> Unit
) = TimedFlow<R>(
onEvent.transform { arg ->
val collector = this
val timedCollector: TimedFlowCollector<R> = object : TimedFlowCollector<R> {
override suspend fun emit(value: R, delay: Long) {
collector.emit(TimedInfo(value, arg.time + delay))
}
) = onEvent.transform<TimedInfo<T>, TimedInfo<R>> { arg ->
val collector = this
val timedCollector: TimedFlowCollector<R> = object : TimedFlowCollector<R> {
override suspend fun emit(value: R, delay: Long) {
collector.emit(TimedInfo(value, arg.time + delay))
}

timedCollector.action(arg.value)
}
)

timedCollector.action(arg.value)
}.asTimedFlow()

fun take(count: Int): TimedFlow<T> {
var consumed = 0
return TimedFlow(onEvent.transform { value ->
return onEvent.transform { value ->
if (consumed++ < count)
emit(value)
})
}.asTimedFlow()
}

}
@@ -38,3 +36,5 @@ class TimedFlow<T>(
interface TimedFlowCollector<in T> {
suspend fun emit(value: T, delay: Long = 0L)
}

fun <T> Flow<TimedInfo<T>>.asTimedFlow() = TimedFlow(this)

+ 3
- 2
audio-automation/src/me/jfenn/audio/utils/extensions/TimedFlow.kt View File

@@ -2,12 +2,13 @@ package me.jfenn.audio.utils.extensions

import kotlinx.coroutines.flow.transform
import me.jfenn.audio.utils.TimedFlow
import me.jfenn.audio.utils.asTimedFlow
import kotlin.math.max

fun <T> TimedFlow<T>.spread(delay: Long = 0, lambda: (T) -> Long = { delay }) : TimedFlow<T> {
var lastTime = 0L
return TimedFlow(onEvent.transform { info ->
return onEvent.transform { info ->
lastTime = max(lastTime + lambda(info.value), info.time)
emit(info.copy(time = lastTime))
})
}.asTimedFlow()
}

Loading…
Cancel
Save