Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created January 30, 2020 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afollestad/d1831a1c651f4733b95f88c32ea04b52 to your computer and use it in GitHub Desktop.
Save afollestad/d1831a1c651f4733b95f88c32ea04b52 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@FlowPreview
@ExperimentalCoroutinesApi
fun main() {
runBlocking {
intervalFlow(
initialProgress = 0,
maxProgress = 10,
period = 300,
loop = true
)
.onEach { println(it) }
.launchIn(this)
}
}
/**
* @param initialProgress The initial value that is emitted.
* @param maxProgress The max value that is emitted.
* @param period The delay between each subsequent emission.
* @param loop Whether or not the timer will restart or stop when the max progress is reached.
* @param minimumProgress If [loop] is true, we return to this value after the [maxProgress] is reached.
*/
@ExperimentalCoroutinesApi
suspend fun intervalFlow(
initialProgress: Long,
maxProgress: Long,
period: Long,
loop: Boolean,
minimumProgress: Long = 0L
): Flow<Long> {
return channelFlow {
var currentValue: Long = initialProgress
while (isActive) {
send(currentValue)
currentValue++
delay(period)
if (currentValue == maxProgress + 1) {
if (!loop) break
currentValue = minimumProgress
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment