State-machine - State machine implementation

Related tags

Kotlin state-machine
Overview

State Machine DSL

Kotlin State Machine DSL implementation heavily inspired by Tinder StateMachine

Sample usage

First, we define states, events, side effects and machine

fun exampleStateMachine() =
    stateMachine<State, Event, Effect>(State.Progress) {
        state<State.Progress> {
            onEvent<Event.OnSearch> { event, _ ->
                transitionTo(
                    State.Progress,
                    Effect.RunSearch(event.query)
                )
            }
            onEvent<Event.OnContent> { event, _ -> transitionTo(State.Content(event.content)) }
        }
        state<State.Content> {
            onEvent<Event.OnRefreshForever> { _, _ -> transitionTo(State.Progress) }
            onEvent<Event.OnRefresh> { _, _ -> transitionTo(State.Progress, Effect.RunFullRefresh) }
            onEvent<Event.OnSearch> { event, _ ->
                transitionTo(
                    State.Progress,
                    Effect.RunSearch(event.query)
                )
            }
            onEvent<Event.OnContent> { event, _ -> transitionTo(State.Content(event.content)) }
        }
    }

sealed class State {
    object Progress : State()
    data class Content(val content: List<String>) : State()
}

sealed class Event {
    object OnRefresh : Event()
    object OnRefreshForever : Event()
    data class OnSearch(val query: String) : Event()
    data class OnContent(val content: List<String>) : Event()
}

sealed class Effect {
    data class RunSearch(val query: String) : Effect()
    object RunFullRefresh : Effect()
}

Then, subscribe to state updates:

private val stateObserver: Subscription? = null 

fun observeState() {
    stateObserver = stateMachine.observe {
        state<State.Content> { 
            onEnter { /* update content view */ }
        }
        state<State.Progress> {
            onEnter { /* show progress view */ }
            onExit { /* hide progress view */ }
        }
        onSideEffect<Effect.RunSearch> {
            val data = filterContent(query)
            stateMachine.postEvent(Event.OnContent(data))
        }
        onSideEffect<Effect.RunFullRefresh> {
            val newData = fetchDataFromServer()
            stateMachine.postEvent(Event.OnContent(newData))
        }
    }
}
// Don't forget to unsubscribe if you no longer need state updates
fun unsubscribe() = stateObserver?.unsubscribe()

Extensions (WIP)

ObservableStateRegistry

An extension for Registry<T>() that allows you to observe a selected State value. It is useful if you want to trigger certain events only when the observed value has changed, regardless of state transition sequence:

sealed class State(val common: Int) {
    data class First(val isLoading: Boolean) : State(1)
    data class Second(val isLoading: Boolean) : State(2)
}

// init your state machine with ObservableStateregistry
val registry = ObservableStateRegistry<State>()
stateMachine(State.First(false), registry = registry) {
    // declare state transitions
}

fun example() {
    registry.selectObserve(State.First::isLoading)
        .onEach {
            // will be triggered whenever State.First::isLoading changes its value
        }
        .launchIn(lifecycleScope)
        
    registry.selectObserve(State::common)
        .onEach {
            // will be triggered every time State changes from First to Second and vice versa
        }
        .launchIn(lifecycleScope)
}

TransientRegistry

An extension for Registry<T>() that allows you to mark some of the states as Transient in order to retain latest non-transient state. Example:

sealed class State {
    data class Content(val title: String) : State()
    object Progress : State(), Transient
    object Error : State()
    object Empty: State()
}

// init your state machine with TransientRegistry
val registry = TransientRegistry<State>()
stateMachine(State.Empty,registry) {
    // declare state transitions
}

// ...
fun example() {
    stateMachine.postEvent(Event.OnContent("test"))
    assert(stateMachine.state is State.Content)
    stateMachine.postEvent(Event.OnRefresh)
    assert(stateMachine.state is State.Progress)
    val latestState = registry.latestNonTransientState
    assert(latestState == State.Content("test"))
}

Lifecycle-aware observer

Subscribe to state updates with provided LifecycleOwner to automatically unsubscribe from events after receiving Lifecycle.Event.ON_DESTROY. By default it uses a kotlinx.coroutines.MainScope() coroutine scope to force updates on main thread. You can substitute it with your own scope.

// in Activity class:
fun observe() {
    viewModel.stateMachine.observeWithLifecycle(
        this, // LifecycleOwner
        myScope // or leave a default scope
    ) {
        state<State.Content> {
            onEnter { /* update UI */ }
        }
    }
}

Download

Gradle

implementation 'com.github.vanspo:state-machine:0.6.2'
implementation 'com.github.vanspo:state-machine-extensions:0.6.2'

Licence

MIT License

Copyright (c) 2020 Ivan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
You might also like...
Advanced State in Jetpack Compose Codelab

Advanced State in Jetpack Compose Codelab This folder contains the source code for the Advanced State in Jetpack Compose Codelab codelab. The project

This repository contains the article describing my attempt to implement a simple state reducer based on Kotlin Flow and an example app that uses it.
This repository contains the article describing my attempt to implement a simple state reducer based on Kotlin Flow and an example app that uses it.

This repository contains the article describing my attempt to implement a simple state reducer based on Kotlin Flow and an example app that uses it.

Simplify mutating "immutable" state models

Mutekt (Pronunciation: /mjuːˈteɪt/, 'k' is silent) "Simplify mutating "immutable" state models" Generates mutable models from immutable model definiti

This Project for how to use  MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture.
This Project for how to use MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture.

Clean-architecture This Project for how to use MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture. Why i should us

📒 NotyKT is a complete 💎Kotlin-stack (Backend + Android) 📱 application built to demonstrate the use of Modern development tools with best practices implementation🦸.
📒 NotyKT is a complete 💎Kotlin-stack (Backend + Android) 📱 application built to demonstrate the use of Modern development tools with best practices implementation🦸.

NotyKT 🖊️ NotyKT is the complete Kotlin-stack note taking 🖊️ application 📱 built to demonstrate a use of Kotlin programming language in server-side

LifecycleMvp 1.2 0.0 Kotlin  is MVP architecture implementation with Android Architecture Components and Kotlin language features
LifecycleMvp 1.2 0.0 Kotlin is MVP architecture implementation with Android Architecture Components and Kotlin language features

MinSDK 14+ Download Gradle Add to project level build.gradle allprojects { repositories { ... maven { url 'https://jitpack.io' }

A kotlin implementation of commutative encryption based on ECC ElGamal encryption over Curve25519

komuta A commutative encryption implementation. This is a naive implementation of commutative encryption using the ElGamal scheme applied over Curve25

Opinionated Redux-like implementation backed by Kotlin Coroutines and Kotlin Multiplatform Mobile

CoRed CoRed is Redux-like implementation that maintains the benefits of Redux's core idea without the boilerplate. No more action types, action creato

Ethereum Web3 implementation for mobile (android & ios) Kotlin Multiplatform development

Mobile Kotlin web3 This is a Kotlin MultiPlatform library that ... Table of Contents Features Requirements Installation Usage Samples Set Up Locally C

Owner
Ivan
Ivan
Kotlin coroutine capable Finite-State Machine (multiplatform)

Comachine Features Kotlin corutines. Event handlers can launch coroutines for collecting external events of performing side effects. Structured concur

Sergej Shafarenka 22 Dec 14, 2022
ClickMachine Fabric - Click Machine for minecraft

Minecraft mod for Fabric Adds one block to the game: Auto Clicker. This autoclic

null 0 Jan 10, 2022
A Java Virtual Machine written in Kotlin

jvm.kotlin A Java Virtual Machine written in Kotlin. Introduction jvm.kotlin is a toy JVM programmed in Kotlin. The main purpose of this project is le

Elements 14 Aug 13, 2022
Kotlin Multiplatform Coffee Machine

Expressus KMM sample project acting as a playground to illustrate what's discussed in these articles: Details Shared Model-View-Intent architecture Fi

Guilherme Delgado 56 Dec 22, 2022
Simple State Machines in Kotlin (KSSM)

Simple State Machines in Kotlin (KSSM) What is this? KSSM (reordered: Kotlin - Simple State Machines) provides an easy and simple DSL (Domain Specific

Milos Marinkovic 22 Dec 12, 2022
💫 Small microservice to handle state changes of Kubernetes pods and post them to Instatus or Statuspages

?? Kanata Small microservice to handle state changes of Kubernetes pods and post them to Instatus or Statuspages ?? Why? I don't really want to implem

Noel 4 Mar 4, 2022
Basic app to use different type of observables StateFlow, Flow, SharedFlow, LiveData, State, Channel...

stateflow-flow-sharedflow-livedata Basic app to use different type of observables StateFlow, Flow, SharedFlow, LiveData, State, Channel... StateFlow,

Raheem 5 Dec 21, 2022
Stresscraft - State-of-art Minecraft stressing software written in Kotlin

StressCraft (W.I.P) State-of-art Minecraft stressing software written in Kotlin.

Cubxity 57 Dec 4, 2022
ConstraintSetChangesTest - Simple project showing Changes of ConstraintSet value as part of mutable state in JetpackCompose.

ConstraintSetChangesTest Simple project showing Changes of ConstraintSet value as part of mutable state in JetpackCompose. Version: implementation

Mateusz Perlak 1 Feb 13, 2022
ScopedState - Android Scoped State With Kotlin

Android Scoped State There is no need for complicated code - just define scopes

Ali Azizi 12 Jan 19, 2022