alakazam.kotlin.core.CoroutineScopeExtensions.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-core Show documentation
Show all versions of kotlin-core Show documentation
A set of useful functions and extensions for Kotlin development.
package alakazam.kotlin.core
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
/**
* Cleans up some of the boilerplate associated with collecting [Flow] streams from a fragment. Without this we'd
* need two indentations before any collected values are dealt with, but this reduces that by one so it's a tad more
* readable.
*/
public fun CoroutineScope.collectFlow(flow: Flow, call: suspend (T) -> Unit): Job =
collectFlow(flow, EmptyCoroutineContext, call)
public fun CoroutineScope.collectFlow(flow: Flow, context: CoroutineContext, call: suspend (T) -> Unit): Job =
launch(context) { flow.collect(call::invoke) }
/**
* Runs an infinite loop of periodic function calls, scoped to the [CoroutineScope]'s lifecycle.
*/
public fun CoroutineScope.launchInfiniteLoop(
loopController: LoopController = InfiniteLoopController,
call: suspend () -> Unit,
): Job = launchInfiniteLoop(EmptyCoroutineContext, loopController, call)
public fun CoroutineScope.launchInfiniteLoop(
context: CoroutineContext,
loopController: LoopController = InfiniteLoopController,
call: suspend () -> Unit,
): Job = launch(context) {
while (loopController.shouldLoop()) {
call()
}
}