commonMain.net.humans.kmm.mvi.EngineLaunchers.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mvi-core Show documentation
Show all versions of mvi-core Show documentation
Simple and concise implementation of Redux/MVI approach by Humans.
The newest version!
package net.humans.kmm.mvi
import co.touchlab.kermit.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
@Suppress("TooGenericExceptionCaught", "LongParameterList", "FunctionNaming")
fun LaunchReduxEngine(
scope: CoroutineScope,
tag: String,
initial: Return,
reducer: ComplexReducer,
effectHandlerFactory: (SendChannel) -> EffectHandler,
errorHandler: ErrorHandler,
): ReduxEngine {
val logger = Logger.withTag(tag)
val messages = Channel(Channel.UNLIMITED)
val states = MutableStateFlow(initial.state)
val effectHandler = effectHandlerFactory.invoke(messages)
effectHandler.handle(initial.effects)
scope.launch {
for (msg in messages) {
try {
val prevState = states.value
val (state, effects) = reducer.invoke(prevState, msg)
logger.logReduce(msg, prevState, state, effects)
states.value = state
effectHandler.handle(effects)
} catch (e: Throwable) {
errorHandler.invoke(e)
}
}
}
return ReduxEngine(messages, states)
}
@Suppress("TooGenericExceptionCaught", "FunctionNaming")
fun LaunchReduxEngine(
scope: CoroutineScope,
tag: String,
initial: S,
reducer: SimpleReducer,
errorHandler: ErrorHandler,
): ReduxEngine {
val logger = Logger.withTag(tag)
val messages = Channel(Channel.UNLIMITED)
val states = MutableStateFlow(initial)
scope.launch {
for (msg in messages) {
try {
val prevState = states.value
val state = reducer.invoke(prevState, msg)
logger.logReduce(prevState, state, msg)
states.value = state
} catch (e: Throwable) {
errorHandler.invoke(e)
}
}
}
return ReduxEngine(messages, states)
}