Predictable state container for Kotlin apps

Related tags

Kotlin redux-kotlin
Overview

Build Status

Redux Kotlin

Redux Kotlin is a predictable state container for Kotlin apps. It is a direct port of the original Redux library for JavaScript, which has excellent documentation at http://redux.js.org/.

The Gist

(Adapted from: https://github.com/reactjs/redux/#the-gist)

The whole state of your app is stored in an object tree inside a single store. The only way to change the state tree is to emit an action, an object describing what happened. To specify how the actions transform the state tree, you write pure reducers.

That's it!

/**
 * This is a reducer, a pure function with (state, action) -> state signature.
 * It describes how an action transforms the state into the next state.
 *
 * The shape of the state is up to you: it can be a primitive, an array, or even an object.
 * The only important part is that you should not mutate the state object, but return a
 * new object if the state changes.
 *
 * In this example, we use a `when` statement and strings, but you can use a helper that
 * follows a different convention if it makes sense for your project. In a real app, you
 * will likely also want to use action types rather than strings, e.g. sealed classes or
 * enum classes.
 */
val reducer = Reducer { state: Int, action: Any ->
	when (action) {
		"Inc" -> state + 1
		"Dec" -> state - 1
		else -> state
	}
}

// Create a Redux store holding the state of your app.
val store = Store.create(reducer, 0)

// You can use subscribe() to update the UI in response to state changes.
// Normally you'd use a view binding library (e.g. redux-rxjava-kotlin and RxBinding) rather
// than subscribe() directly.
store.subscribe {
	println("${store.getState()}")
}

// The only way to mutate the internal state is to dispatch an action.
// The actions can be serialized, logged or stored and later replayed.
store.dispatch("Inc")
// 1
store.dispatch("Inc")
// 2
store.dispatch("Dec")
// 1

Download

repositories {
	maven { url "https://jitpack.io" }
}
compile 'com.github.pardom:redux-kotlin:<version>'

Snapshots of the development version are available the by using -SNAPSHOT as the version.

Samples

Middleware

License

 Copyright (C) 2016 Michael Pardo

 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
  • undoable feature

    undoable feature

    Hi @pardom, first thanks for you amazing lib! I was wondering if you planned to add a built-in "undoable" feature to this lib (or creating a dedicated one) like described here for instance? Thanks again, Thomas

    opened by otomatik 4
  • Fixes #11. Split jvm/js builds into two modules.

    Fixes #11. Split jvm/js builds into two modules.

    Conflicts exist when trying to target both builds within the same module. kotlin-stdlib is not a Kotlin JS jar and neither are any of the test dependencies. I'm not sure if this is the preferred way to fix this, but it works for now.

    opened by pardom-zz 3
  • Development env. setup guidelines

    Development env. setup guidelines

    Hey, I like very much your impl. but when trying to dig a bit more into it I stumbled upon issues with the IDE.

    The project does not compile w/ IJ : the following imports can't be found.

    import org.jetbrains.spek.api.Spek
    import org.mockito.Mockito.mock
    import org.mockito.Mockito.times
    import org.mockito.Mockito.verify
    

    It would be interesting to either provide setup instructions.

    Note : it does work with gradle in command line.

    opened by glung 3
  • Duplicate Files

    Duplicate Files

    I am getting an error on build. I am trying to use this redux-kotlin library along with redux-optimist-kotlin.

    Error:

    Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
    > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/lib_main.kotlin_module
      	File1: /Users/matt/.gradle/caches/modules-2/files-2.1/com.github.pardom/redux-optimist-kotlin/1.2.2/30629e4a113de83440950288e87185072ff82fc9/redux-optimist-kotlin-1.2.2.jar
      	File2: /Users/matt/.gradle/caches/modules-2/files-2.1/com.github.pardom/redux-kotlin/1.2.1/8a0580e9e0a9ede0aa9a9295b69edcac4ec3db10/redux-kotlin-1.2.1.jar
    

    Project build.gradle

    dependencies {
    
        final SUPPORT_LIBRARY_VERSION = '25.1.0'
    
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:25.1.0'
        compile 'com.android.support:support-v4:25.1.0'
        compile "com.android.support:design:$SUPPORT_LIBRARY_VERSION"
    
        compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    
        compile 'com.github.pardom:redux-kotlin:1.2.1'
        compile 'com.github.pardom:redux-optimist-kotlin:1.2.2'
    }
    

    app build.gradle

    allprojects {
        repositories {
            jcenter()
            maven { url "https://jitpack.io" }
        }
    }
    
    opened by horsejockey 1
  • Integrate with jvm-redux-api specs.

    Integrate with jvm-redux-api specs.

    ▲▲▲▲ DNM : it is building against a non-released branch ▲▲▲▲▲

    Scope

    Integrate the tests implemented in jvm-redux-api

    • add dependency
    • add tests

    Details

    cf Cf https://github.com/jvm-redux/jvm-redux-api/pull/13

    opened by glung 1
  • gradle dependency in README incorrect

    gradle dependency in README incorrect

    Think it should read:

    compile 'com.github.pardom:redux-kotlin:1.1.0'
    

    rather than:

    'com.github.pardom.redux-kotlin:lib:1.1.0'
    

    btw really like your implementation of redux from the quick look I've had at it.

    opened by langleyd 1
  • How to pass a sealed class

    How to pass a sealed class

    This is not exactly an issue, more of a documentation request as I couldn't seem to figure out how to do it just fiddling around.

    I have a sealed class I am using as an action:

    class SelectClient(var id:String? = "") {
        companion object
    }
    

    My reducer looks like this:

    val rwaReducer = Reducer { state: RWAState, action: Any ->
        when (action) {
            SelectClient -> {
                val action = action as SelectClient
                println(action.id) // Doesn't print anything here
                state
            }
            else ->
                state
        }
    }
    

    When I dispatch an initialized class variable, it doesn't do anything in the reducer, looks like it doesn't recognize the class as the action passed

    var action = SelectClient()
    action.id = "SomeClient"
    rwaStore.dispatch(action)
    

    Perhaps I am dispatching wrongly? Any help would be appreciated! :)

    opened by robert-cronin 1
  • Problem with versions 1.1.0 and up

    Problem with versions 1.1.0 and up

    With this versions, when I try to import your library it only allows me to import (Reducer or Store classes, for example) from "jvm-redux-api".

    I don't know why it happens and if this happens only to me.

    Version 1.0.3 allows me to import the correct classes and use the library.

    opened by inlacou 1
  • java.lang.NoSuchMethodError: redux.api.Store.getState

    java.lang.NoSuchMethodError: redux.api.Store.getState

    I'm having trouble properly creating the store. Whenever I call getState on the store, I get the error shown below. It prints out that the mainStore is of type redux.MiddlewareKt$applyMiddleware$1$1$1.

    // TODO: initialize AppState from file if available
    val previousState = AppState()
    val mainStore = createStore(AppReducer(), previousState, applyMiddleware(MyMiddleware<AppState>()))
    Log.e(getClass().toString(), "Store's class type is: " + mainStore.getClass().toString());
    AppState state = mainStore.getState();
    

    02-07 11:18:54.354 3556-3556/? E/class com.mypackage.MainApplication: Store's class type is: class redux.MiddlewareKt$applyMiddleware$1$1$1 02-07 11:18:54.354 3556-3556/? D/AndroidRuntime: Shutting down VM 02-07 11:18:54.354 3556-3556/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x9cc93b20) 02-07 11:18:54.354 3556-3556/? E/AndroidRuntime: FATAL EXCEPTION: main Process: com.mypackage, PID: 3556 java.lang.NoSuchMethodError: redux.api.Store.getState

    I've also tried without the middleware. Without the middleware, it says the type is redux.StoreKt$createStore$creator$1$1.

    opened by mikecole20 2
Releases(1.2.0)
Owner
Michael Pardo
Michael Pardo
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
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
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
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
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
🔴 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
💫 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
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
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
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

Shreyas Patil 179 Nov 30, 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
Cross-platform framework for building truly native mobile apps with Java or Kotlin. Write Once Run Anywhere support for iOS, Android, Desktop & Web.

Codename One - Cross Platform Native Apps with Java or Kotlin Codename One is a mobile first cross platform environment for Java and Kotlin developers

Codename One 1.4k Jan 9, 2023
Library to use Kotlin Coroutines from Swift code in KMP apps

KMP-NativeCoroutines A library to use Kotlin Coroutines from Swift code in KMP apps. Flows Kotlin Create an extension property to expose the Flow as a

Rick Clephas 508 Jan 3, 2023
Udacity Free course: Developing Android Apps with Kotlin

Room - SleepQualityTracker app This is the toy app for Lesson 6 of the Android App Development in Kotlin course on Udacity. SleepQualityTracker The Sl

Reinaldo  Salazar 0 Nov 6, 2021
This lib implements the most common CoroutineScopes used in Android apps.

AndroidCoroutineScopes Starting from 0.26.0 release we should define a scope for new coroutines (docs). To avoid this boilerplate code I've created th

Adriel Café 15 Oct 3, 2022
D-KMP Architecture official sample: it uses a shared KMP ViewModel and Navigation for Compose and SwiftUI apps.

D-KMP architecture - official sample This is the official sample of the D-KMP architecture, presenting a simple master/detail app, for Android, iOS an

null 594 Jan 3, 2023
🚀 Native iOS- and Android- Apps with JavaScript

Titanium Welcome to the Titanium open source project. Titanium provides a mature platform for developers to build completely native cross-platform mob

Team Appcelerator 2.6k Jan 4, 2023