🔴 A non-deterministic finite-state machine for Android & JVM that won't let you down

Overview

JitPack Android API Bitrise Codacy Codecov kotlin ktlint License MIT

HAL is a non-deterministic finite-state machine for Android & JVM built with Coroutines StateFlow and LiveData.

Why non-deterministic?

Because in a non-deterministic finite-state machine, an action can lead to one, more than one, or no transition for a given state. That way we have more flexibility to handle any kind of scenario.

Use cases:

  • InsertCoin transition to Unlocked
  • LoadPosts transition to Loading then transition to Success or Error
  • LogMessage don't transition

turnstile diagram

Why HAL?

It's a tribute to HAL 9000 (Heuristically programmed ALgorithmic computer), the sentient computer that controls the systems of the Discovery One spacecraft.

"I'm sorry, Dave. I'm afraid I can't do that." (HAL 9000)


This project started as a library module in one of my personal projects, but I decided to open source it and add more features for general use. Hope you like!

Usage

First, declare your Actions and States. They must implement HAL.Action and HAL.State respectively.

sealed class MyAction : HAL.Action {

    object LoadPosts : MyAction()
    
    data class AddPost(val post: Post) : MyAction()
}

sealed class MyState : HAL.State {

    object Init : MyState()
    
    object Loading : MyState()
    
    data class PostsLoaded(val posts: List<Post>) : MyState()
    
    data class Error(val message: String) : MyState()
}

Next, implement the HAL.StateMachine<YourAction, YourState> interface in your ViewModel, Presenter, Controller or similar.

The HAL class receives the following parameters:

  • The initial state
  • A CoroutineScope (tip: use the built in viewModelScope)
  • An optional CoroutineDispatcher to run the reducer function (default is Dispatcher.DEFAULT)
  • A reducer function, suspend (action: A, state: S) -> Unit, where:
    • suspend: the reducer runs inside a CoroutineScope, so you can run IO and other complex tasks without worrying about block the Main Thread
    • action: A: the action emitted to the state machine
    • state: S: the current state of the state machine

You should handle all actions inside the reducer function. Call transitionTo(newState) or simply +newState whenever you need to change the state (it can be called multiple times).

class MyViewModel(private val postRepository: PostRepository) : ViewModel(), HAL.StateMachine<MyAction, MyState> {

    override val stateMachine by HAL(MyState.Init, viewModelScope) { action, state ->
        when (action) {
            is MyAction.LoadPosts -> {
                +MyState.Loading
                
                try {
                    // You can run suspend functions without blocking the Main Thread
                    val posts = postRepository.getPosts()
                    // And emit multiple states per action
                    +MyState.PostsLoaded(posts)
                } catch(e: Exception) {
                    +MyState.Error("Ops, something went wrong.")
                }
            }
            
            is MyAction.AddPost -> {
                /* Handle action */
            }
        }
    }
}

Finally, choose a class to emit actions to your state machine and observe state changes, it can be an Activity, Fragment, View or any other class.

class MyActivity : AppCompatActivity() {

    private val viewModel by viewModels<MyViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
    
        // Easily emit actions to your State Machine
        // You can all use: viewModel.emit(MyAction.LoadPosts)
        loadPostsBt.setOnClickListener {
            viewModel += MyAction.LoadPosts
        }
        
        // Observe and handle state changes
        viewModel.observeState(lifecycleScope) { state ->
            when (state) {
                is MyState.Init -> showWelcomeMessage()
                
                is MyState.Loading -> showLoading()
                
                is MyState.PostsLoaded -> showPosts(state.posts)
                
                is MyState.Error -> showError(state.message)
            }
        }
    }
}

If you want to use a LiveData-based state observer, just pass your LifecycleOwner to observeState(), otherwise HAL will use the default Flow-based state observer.

// Observe and handle state changes backed by LiveData
viewModel.observeState(lifecycleOwner) { state ->
    // Handle state
}

Single source of truth

Do you like the idea of have a single source of truth, like the Model in The Elm Architecture or the Store in Redux? I have good news: you can do the same with HAL!

Instead of use a sealed class with multiple states just create a single data class to represent your entire state:

sealed class MyAction : HAL.Action {
    // Declare your actions as usual
}

// Tip: use default parameters to represent your initial state
data class MyState(
    val posts: List<Post> = emptyList(),
    val loading: Boolean = false,
    val error: String? = null
) : HAL.State

Now, when handling the emitted actions use state.copy() to change your state:

override val stateMachine by HAL(MyState(), viewModelScope) { action, state ->
    when (action) {
        is NetworkAction.LoadPosts -> {
            +state.copy(loading = true)

            try {
                val posts = postRepository.getPosts()
                +state.copy(posts = posts)
            } catch (e: Throwable) {
                +state.copy(error = "Ops, something went wrong.")
            }
        }
        
        is MyAction.AddPost -> {
            /* Handle action */
        }
    }
}

And finally you can handle the state as a single source of truth:

viewModel.observeState(lifecycleScope) { state ->
    showPosts(state.posts)
    setLoading(state.loading)
    state.error?.let(::showError)
}

Custom StateObserver

If needed, you can also create your custom state observer by implementing the StateObserver<S> interface:

class MyCustomStateObserver<S : HAL.State>(
    private val myAwesomeParam: MyAwesomeClass
) : HAL.StateObserver<S> {

    override fun observe(stateFlow: Flow<S>) {
        // Handle the incoming states
    }
}

And to use, just create an instance of it and pass to observeState() function:

viewModel.observeState(MyCustomStateObserver(myAwesomeParam))

Import to your project

  1. Add the JitPack repository in your root build.gradle at the end of repositories:
allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
  1. Next, add the desired dependencies to your module:
dependencies {
    // Core with Flow state observer
    implementation "com.github.adrielcafe.hal:hal-core:$currentVersion"

    // LiveData state observer only
    implementation "com.github.adrielcafe.hal:hal-livedata:$currentVersion"
}

Current version: JitPack

Platform compatibility

hal-core hal-livedata
Android
JVM
You might also like...
Basic app to use different type of observables StateFlow, Flow, SharedFlow, LiveData, State, Channel...
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,

Stresscraft - State-of-art Minecraft stressing software written in Kotlin

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

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

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

Events Calendar is a user-friendly library that helps you achieve a cool Calendar UI with events mapping. You can customise every pixel of the calendar as per your wish and still achieve in implementing all the functionalities of the native android calendar in addition with adding dots to the calendar which represents the presence of an event on the respective dates. It can be done easily, you are just a few steps away from implementing your own badass looking Calendar for your very own project!
👋 A common toolkit (utils) ⚒️ built to help you further reduce Kotlin boilerplate code and improve development efficiency. Do you think 'kotlin-stdlib' or 'android-ktx' is not sweet enough? You need this! 🍭

Toolkit [ 🚧 Work in progress ⛏ 👷 🔧️ 🚧 ] Snapshot version: repositories { maven("https://s01.oss.sonatype.org/content/repositories/snapshots") }

Comments
Releases(1.0.3)
Owner
Adriel Café
Remote Android Developer
Adriel Café
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
Carousel Recyclerview let's you create carousel layout with the power of recyclerview by creating custom layout manager.

Carousel Recyclerview Create carousel effect in recyclerview with the CarouselRecyclerview in a simple way. Including in your project Gradle Add below

Jack and phantom 514 Jan 8, 2023
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
Android Application that let users select 2 currencies with the amount to convert

Currency Converter Android Application that let users select 2 currencies with the amount to convert and have Historical data for 2 currencies of thei

Ahmed Khaled Mohllal 6 May 22, 2022
NFST - Non-Fungible Simian Token

NFST - Non-Fungible Simian Token A centralized ledger on the blockchain to recor

null 2 Mar 4, 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
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