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

commonMain.net.humans.kmm.mvi.EngineLaunchers.kt Maven / Gradle / Ivy

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)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy