Simplify mutating "immutable" state models

Overview

Mutekt

(Pronunciation: /mjuːˈteɪt/, 'k' is silent)

"Simplify mutating "immutable" state models"

Generates mutable models from immutable model definitions. It's based on Kotlin's Symbol Processor (KSP). This is inspired from the concept Redux and Immer from JS world that let you write simpler immutable update logic using "mutating" syntax which helps simplify most reducer implementations. So you just need to focus on actual development and Mutekt will write boilerplate for you! 😎

Like this ⬇️

Mutekt Usage Example

Usage

Try out the example app to see it in action.

1. Apply annotation and generate model

Declare a state model as an interface and apply @GenerateMutableModel annotation to it.

Example:

@GenerateMutableModel
interface NotesState {
    val isLoading: Boolean
    val notes: List<String>
    val error: String?
}
// You can also apply annotation `@Immutable` if using for Jetpack Compose UI model.

Once done, 🔨 Build project and mutable model will be generated for the immutable definition by KSP.

2. Simply mutate and get immutable state

The mutable model can be created with the factory function which is generated with the name of an interface with prefix Mutable. For example, if interface name is ExampleState then method name for creating mutable model will be MutableExampleState() and will have parameters in it which are declared as public properties in the interface.

/**
 * Instance of mutable model [MutableNotesState] which is generated with Mutekt.
 */
private val _state = MutableNotesState(isLoading = true, notes = emptyList(), error = null)

fun setLoading() {
    _state.isLoading = true
}

fun setNotes() {
    _state.apply {
        isLoading = false
        notes = listOf("Lorem Ipsum")
    }
}

3. Getting reactive immutable value updates

To get immutable instance with reactive state updates, use method asStateFlow() which returns instance of StateFlow<T>. Whenever any field of Mutable model is updated with new value, this StateFlow gets updated with new immutable state value.

val state: StateFlow<NotesState> = _state.asStateFlow()

Properties of immutable instance implemented by Mutekt:

  • Immutable model implementation promises to be truly Immutable i.e. once instance is created, its properties will never change.
  • Implementation is actually a data class under the hood i.e. having equals() and hashCode() already overridden.

Setting up Mutekt in the project

1. Gradle setup

1.1 Enable KSP in module

In order to support code generation at compile time, enable KSP support in the module.

plugins {
    id 'com.google.devtools.ksp' version '1.7.10-1.0.6'
}

1.2 Add dependencies

In build.gradle of app module, include this dependency

repositories {
    mavenCentral()
}

dependencies {
    implementation("dev.shreyaspatil.mutekt:mutekt-core:$mutektVersion")
    ksp("dev.shreyaspatil.mutekt:mutekt-codegen:$mutektVersion")
    
    // Include kotlin coroutine to support usage of StateFlow 
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
}

You can find the latest version and changelogs in the releases.

1.3 Include generated classes in sources

Note
In order to make IDE aware of generated code, it's important to include KSP generated sources in the project source sets.

Include generated sources as follows:

Gradle (Groovy)
kotlin {
    sourceSets {
        main.kotlin.srcDirs += 'build/generated/ksp/main/kotlin'
        test.kotlin.srcDirs += 'build/generated/ksp/test/kotlin'
    }
}
Gradle (KTS)
kotlin {
    sourceSets.main {
        kotlin.srcDir("build/generated/ksp/main/kotlin")
    }
    sourceSets.test {
        kotlin.srcDir("build/generated/ksp/test/kotlin")
    }
}
Android (Gradle - Groovy)
android {
    applicationVariants.all { variant ->
        kotlin.sourceSets {
            def name = variant.name
            getByName(name) {
                kotlin.srcDir("build/generated/ksp/$name/kotlin")
            }
        }
    }
}
Android (Gradle - KTS)
android {
    applicationVariants.all {
        kotlin.sourceSets {
            getByName(name) {
                kotlin.srcDir("build/generated/ksp/$name/kotlin")
            }
        }
    }
}

See also

👨‍💻 Development

Clone this repository and import in IntelliJ IDEA (any edition) or Android Studio.

Module details

  • mutekt-core: Contain core annotation and interface for mutekt
  • mutekt-codegen: Includes sources for generating mutekt code with KSP
  • example: Example application which demonstrates usage of this library.

Verify build

  • To verify whether project building or not: ./gradlew build.
  • To verify code formatting: ./gradlew spotlessCheck.
  • To reformat code with Spotless: ./gradlew spotlessApply.

🙋‍♂️ Contribute

Read contribution guidelines for more information regarding contribution.

💬 Discuss

Have any questions, doubts or want to present your opinions, views? You're always welcome. You can start discussions.

📝 License

Copyright 2022 Shreyas Patil

Licensed under the Apache License, Version 2.0 (the "License");

you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Comments
  • KMP support

    KMP support

    Fixes #10

    Adds KMP support including Android, JVM, JS (both browser and NodeJS), iOS (needs a macOS host to build&publish)

    I've added the application plugin to the example project to check if nothing broken. You can run ./gradlew run

    opened by DVDAndroid 5
  • How do you do atomic update with this ?

    How do you do atomic update with this ?

    Like the reddit comment in this.

    This seems like it could break data invariants since it pushes updates on every data field update.

    Eg if you depend on a data model being in either state A or B, now it can be both or neither since you must account for intermediary steps

    enhancement help wanted 
    opened by thegarlynch 3
  • A question about setting multiple parameters

    A question about setting multiple parameters

    Greetings!

    Let's assume we have:

    interface HomeScreenState { val isLoading: Boolean val title: String val avatar: String val items: List val selectedItem: Any? }

    and a method like

    fun update() { _state.isLoading = true val data = getSomeData() _state.title = data.title _state.avatar = data.avatar _state.items = data.items _state.selectedItem = data.items.firstOrNull() }

    or

    fun update() { _state.isLoading = true val data = getSomeData() _state.apply { title = data.title avatar = data.avatar items = data.items selectedItem = data.items.firstOrNull() } }

    How many times would state.collect {} block be called in a view/widget in both cases?

    opened by leffsu 2
  • Release v1.0.0-alpha03

    Release v1.0.0-alpha03

    Changelog

    • #9:

    Added support for updating multiple state fields atomically with Mutekt-generated mutable model. Just use update{} on the instance of mutable model.

    Example:

    val state = MutableNotesState(...)
    
    state.update {
      isLoading = false
      notes = listOf("Lorem Ipsum")
    }
    
    • #2

    Added test cases for core and codegen modules.

    opened by PatilShreyas 0
  • [#9] Add support for atomic updates with Mutekt models

    [#9] Add support for atomic updates with Mutekt models

    Summary

    • Added support for atomic updates for multiple state fields of a Mutekt model. Fixes: #9 As discussed: #12

    For example: If the following is a model

    @GenerateMutableModel
    interface NotesState {
      val loading: Boolean
      val notes: List<String>
      val error: String?
    }
    

    Then, atomic update will be possible with update{} method:

    val notesState = MutableNotesState(...)
    
    notesState.update {
      loading = false
      notes = listOf("Lorem Ipsum")
    }
    

    Here, on mutating loading and notes field of a state, only a a single value will be emitted as a state without affecting the current coroutine dispatcher.

    • Added interfaces MutektState and MutektMutableState. Mutable model implements it.
    opened by PatilShreyas 0
  • Change StateFlow<> to StateFlow<T>

    Change StateFlow<> to StateFlow

    Change StateFlow<> to StateFlow<T> at README.md. This looks a bit more natural. And this is also the signature of the StateFlow interface.

    And thanks for the good open source! Please close this PR if intended.

    opened by jisungbin 0
  • KMP support

    KMP support

    This library can be easily converted to a multiplatform one since it uses kotlinx-coroutines (with 100% multiplatform support) and KSP that can generate common code. So, it will be possible to use the same code for multiple platforms such as:

    • Android
    • JVM (ex: Jetbrains Compose applications)
    • JS (ex: React or Jetbrains Compose applications)
    • iOS (shared view model with Android)
    enhancement 
    opened by DVDAndroid 0
  • Incorrectly generated code using a typealias as a type paramter.

    Incorrectly generated code using a typealias as a type paramter.

    Invalid code is generated when an interface uses a typealias as a type paramter.

    typealias SomeTypeAlias = TypeA<out TypeB>
    
    @GenerateMutableModel
    interface UiState {
        val list: List<SomeTypeAlias>
    }
    

    Generated code

    public fun MutableUiState(
        list: List<SomeTypeAlias<out TypeB>>
    )
    

    Expected

    public fun MutableUiState(
        list: List<SomeTypeAlias>
    )
    
    bug blocked 
    opened by tevjef 2
Releases(v1.0.0-alpha03)
  • v1.0.0-alpha03(Sep 13, 2022)

    What's Changed

    • [#9] Added support for updating multiple state fields atomically with Mutekt-generated mutable model. Just use update{} on the instance of mutable model.

    Example:

    val state = MutableNotesState(...)
    
    state.update {
      isLoading = false
      notes = listOf("Lorem Ipsum")
    }
    

    Full Changelog: https://github.com/PatilShreyas/mutekt/compare/v1.0.0-alpha02...v1.0.0-alpha03

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0-alpha02(Jul 31, 2022)

  • v1.0.0-alpha01(Sep 13, 2022)

Owner
Shreyas Patil
💼Android Engineer @ Paytm Insider, 👨‍💻Google Developer Expert for Android, ❤️Kotlin, 👨‍🚀Organizer @KotlinMumbai
Shreyas Patil
Clean MVVM with eliminating the usage of context from view models by introducing hilt for DI and sealed classes for displaying Errors in views using shared flows (one time event), and Stateflow for data

Clean ViewModel with Sealed Classes Following are the purposes of this repo Showing how you can remove the need of context in ViewModels. I. By using

Kashif Mehmood 22 Oct 26, 2022
Mogen - Converts Kotlin models to other languages

Mogen is a small library that converts Kotlin's models to other programming lang

elevup 3 Jun 8, 2022
🔓 Kotlin version of the popular google/easypermissions wrapper library to simplify basic system permissions logic on Android M or higher.

EasyPermissions-ktx Kotlin version of the popular googlesample/easypermissions wrapper library to simplify basic system permissions logic on Android M

Madalin Valceleanu 326 Dec 23, 2022
Gradle plugin for simplify Kotlin Multiplatform mobile configurations

Mobile Multiplatform gradle plugin This is a Gradle plugin for simple setup of Kotlin Multiplatform mobile Gradle modules. Setup buildSrc/build.gradle

IceRock Development 78 Sep 27, 2022
Oratio Library for Android Studio helps you simplify your Android TTS codes

Oratio Oratio is a library for Android Studio. This library is useful to a number of developers who are currently making apps using android TTS(Text-T

Jacob Lim 1 Oct 28, 2021
General purpose parsing framework. Simplify parsing of text

General purpose parsing framework. Simplify parsing of text. Allows capture complex nested formats with simple and human-readable syntax.

Roman 1 Nov 16, 2021
Gits-android-extensions - A collection of Kotlin extensions to simplify Android development

gits-android-extensions A collection of Kotlin extensions to simplify Android de

GITS Indonesia 3 Feb 3, 2022
🔴 A non-deterministic finite-state machine for Android & JVM that won't let you down

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

Adriel Café 73 Nov 28, 2022
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
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
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
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
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

Carlos Barrios 1 May 12, 2022
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.

Maciej Sady 18 Dec 29, 2022
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

Kareem Aboelatta 10 Dec 13, 2022