Created
January 30, 2020 22:25
-
-
Save afollestad/d1831a1c651f4733b95f88c32ea04b52 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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