All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.pro.respawn.flowmvi.modules.IntentModule.kt Maven / Gradle / Ivy

Go to download

A Kotlin Multiplatform MVI library based on plugins that is simple, fast, powerful & flexible

There is a newer version: 3.0.0
Show newest version
package pro.respawn.flowmvi.modules

import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.yield
import pro.respawn.flowmvi.api.IntentReceiver
import pro.respawn.flowmvi.api.MVIIntent

internal interface IntentModule : IntentReceiver {

    suspend fun awaitIntents(onIntent: suspend (intent: I) -> Unit)
}

internal fun  intentModule(
    parallel: Boolean,
    capacity: Int,
    overflow: BufferOverflow,
): IntentModule = IntentModuleImpl(parallel, capacity, overflow)

private class IntentModuleImpl(
    private val parallel: Boolean,
    capacity: Int,
    overflow: BufferOverflow,
) : IntentModule {

    private val intents = Channel(capacity, overflow)

    override suspend fun emit(intent: I) = intents.send(intent)
    override fun send(intent: I) {
        intents.trySend(intent)
    }

    override suspend fun awaitIntents(onIntent: suspend (intent: I) -> Unit) = coroutineScope {
        for (intent in intents) {
            // must always suspend the current scope to wait for intents
            if (parallel) launch {
                onIntent(intent)
            } else onIntent(intent)
            yield()
        }
    }
}