commonMain.pro.respawn.flowmvi.modules.IntentModule.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of core-jvm Show documentation
Show all versions of core-jvm Show documentation
A Kotlin Multiplatform MVI library based on plugins that is simple, fast, powerful & flexible
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()
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy