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

commonMain.pro.respawn.flowmvi.plugins.ReducePlugin.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.plugins

import pro.respawn.flowmvi.api.FlowMVIDSL
import pro.respawn.flowmvi.api.MVIAction
import pro.respawn.flowmvi.api.MVIIntent
import pro.respawn.flowmvi.api.MVIState
import pro.respawn.flowmvi.api.PipelineContext
import pro.respawn.flowmvi.api.StorePlugin
import pro.respawn.flowmvi.dsl.StoreBuilder
import pro.respawn.flowmvi.dsl.plugin

/**
 * Default name for [reducePlugin].
 * This is hardcoded so that multiple [reduce] invocations are not allowed w/o
 * explicit consent of the user as most often multiple reducers will conflict with each other.
 * Provide your own name if you want to have multiple reducers.
 */
public const val ReducePluginName: String = "ReducePlugin"

/**
 * An operation that processes incoming [MVIIntent]s
 */
public typealias Reduce = suspend PipelineContext.(intent: I) -> Unit

/**
 * Create and install a [reducePlugin].
 *
 * Name is hardcoded because usually multiple reducers are not used.
 *
 * Provide your own name if you want to have multiple reducers.
 *
 * Events will be consumed (not passed along the chain of plugins) if [consume] is true (true by default).
 */
@FlowMVIDSL
public inline fun  StoreBuilder.reduce(
    consume: Boolean = true,
    name: String = ReducePluginName,
    crossinline reduce: Reduce,
): Unit = install(reducePlugin(consume, name, reduce))

/**
 * Create  a new plugin that simply invokes [StorePlugin.onIntent], processes it and does not change the intent.
 *
 * To change the intent, either create your own [plugin] or use [PipelineContext] to manage the store.
 *
 * Name is hardcoded because usually multiple reducers are not used.
 *
 * Provide your own name if you want to have multiple reducers.
 *
 * Events will be consumed (not passed along the chain of plugins) if [consume] is true (true by default).
 **/
@FlowMVIDSL
public inline fun  reducePlugin(
    consume: Boolean = true,
    name: String = ReducePluginName,
    crossinline reduce: Reduce,
): StorePlugin = plugin {
    this.name = name
    onIntent {
        reduce(it)
        it.takeUnless { consume }
    }
}