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

Overview

CoRed

Kotlin Maven Central

CoRed is Redux-like implementation that maintains the benefits of Redux's core idea without the boilerplate. No more action types, action creators, switch statements or complicated setup. It is Kotlin and it has coroutine supported right out-of-the-box. Also, yes, it is Kotlin Multiplatform supported (https://kotlinlang.org/docs/mpp-intro.html)

Features

CoRed is an opinionated way to setup the Redux implementation. Why we need CoRed? Redux is an amazing state management tool. However, some might find it to be too complicated or hard to use/understand, because the plain vanilla Redux-like implementation is quite boilerplate-y. There is an even page from the official Redux.js on how to reduce the boilerplate. That's why we develop CoRed.

In CoRed's implementation, we are trying to solve the same problem with original Redux by introducing the more friendly API, then translating that into Kotlin in order to be a bit more accessible to mobile dev to use in their projects.

Installation

Add mavenCentral into your dependencies' repositories configuration

repositories {
    mavenCentral()
    // ...
}

Then, just add the dependency to your commonMain dependencies

commonMain {
    dependencies {
        // ...
        implementation("com.github.kittinunf.cored:cored:«version»")
    }
}

How to set this up?

Good question. Let's try to set up a minimal example with StoreAdapter with an ability to show a list data from the network.

Assuming that we have a Repository class that already connects to the API somewhere, eg. Comments, we can use it to fetch the data for our store.

interface CommentRepository {
    suspend fun getComments(): List<String>
}

Redux with CoRed implementation (the setup part should be under 35~ lines)

class CommentsState(val comments: List<String>? = null) : State

object Load : Identifiable
class SetComments(val comments: List<String>?) : Identifiable

val repository: CommentRepository // get repository somewhere e.g. manually create, DI, or 3rd party library

val store = Store(
    scope = viewScope,
    initialState = CommentsState(),
    reducers = mapOf(
        "SetComments" to Reducer { currentState: CommentsState, action: SetComments ->
            currentState.copy(comments = action.comments)
        }
    ),
    middlewares = mapOf(
        "Load" to Middleware { order: Order, store: Store, state: CommentsState, action: Load ->
            if (order == Order.AfterReduced) {
                scope.launch {
                    val result = repository.getComments()
                    if (result.isSuccess) {
                        store.dispatch(SetComments(result.value))
                    } else {
                        store.dispatch(SetComments(null))
                    }
                }
            }
        }
    )
)

Usage

// in Coroutine scope - you can observe state changes with `collect`
store.states
    .collect {
        /** This should return { comments : [ {
        "postId": 1,
        "id": 1,
        "name": "id labore ex et quam laborum",
        "email": "[email protected]",
        "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
        }, ... ] }
         **/
        println(it)
    }

// dispatch an action 
store.dispatch(Load)

For documentation, check more details in the README

For example, check more tests in the commonTest folder.

Credits

CoRed is brought to you by contributors.

Licenses

CoRed is released under the MIT license.

You might also like...
Recycler-coroutines - RecyclerView Auto Add Data Using Coroutines

Sample RecyclerView Auto Add With Coroutine Colaborator Very open to anyone, I'l

A simple, classic Kotlin MVI implementation based on coroutines with Android support, clean DSL and easy to understand logic

A simple, classic Kotlin MVI implementation based on coroutines with Android support, clean DSL and easy to understand logic

Crunch-Mobile - A Food Delivery Mobile App which uses Modern App Architecture Pattern, Firebase And a Simple Restful Api
Crunch-Mobile - A Food Delivery Mobile App which uses Modern App Architecture Pattern, Firebase And a Simple Restful Api

Crunch-Mobile This is a Food Delivery Mobile App which uses Modern App Architect

KaMP Kit by Touchlab is a collection of code and tools designed to get your mobile team started quickly with Kotlin Multiplatform.
KaMP Kit by Touchlab is a collection of code and tools designed to get your mobile team started quickly with Kotlin Multiplatform.

KaMP Kit Welcome to the KaMP Kit! About Goal The goal of the KaMP Kit is to facilitate your evaluation of Kotlin Multiplatform (aka KMP). It is a coll

Location Service Manager for Kotlin Multiplatform Mobile iOS and android
Location Service Manager for Kotlin Multiplatform Mobile iOS and android

Location Service Manager for Kotlin Multiplatform Mobile iOS and android Features Provides simple permission settings Dramatically reduce the amount o

Kotlin Multiplatform Mobile demo for Android and iOS - app for viewing Cat pictures
Kotlin Multiplatform Mobile demo for Android and iOS - app for viewing Cat pictures

CatViewerDemo Android demo iOS demo Kotlin Multiplatform Mobile demo for Android and iOS. App for viewing Cat pictures from Cats API. This sample show

A local storage management library for Kotlin Multiplatform Mobile iOS and android
A local storage management library for Kotlin Multiplatform Mobile iOS and android

A local storage management library for Kotlin Multiplatform Mobile iOS and android Features iOS and Android local storage in one interface Provides ge

MangaKu App Powered by Kotlin Multiplatform Mobile, Jetpack Compose, and SwiftUI
MangaKu App Powered by Kotlin Multiplatform Mobile, Jetpack Compose, and SwiftUI

MangaKu 🤖 Introduction MangaKu App Powered by Kotlin Multiplatform Mobile, Jetpack Compose, and SwiftUI Module core: data and domain layer iosApp: io

Kotlin Multiplatform is an SDK for cross-platform mobile development, which enables teams to use the same business logic in both Android and iOS client applications.
Kotlin Multiplatform is an SDK for cross-platform mobile development, which enables teams to use the same business logic in both Android and iOS client applications.

Kotlin Multiplatform is an SDK for cross-platform mobile development, which enables teams to use the same business logic in both Android and iOS client applications.

Comments
  • Reorganise code structure

    Reorganise code structure

    What has changed?

    • Moved code into separate files and packages
    • Renamed class Store to ReduxStore and interface StoreType to Store

    Why it has changed?

    • To (hopefully) increase code readability :)
    opened by zalewskise 4
  • :memo: [Suggestion] Drop using GlobalScope as a default value for Store factory functions

    :memo: [Suggestion] Drop using GlobalScope as a default value for Store factory functions

    What has changed?

    • Removed GlobalScope as a default value for Store factory functions

    Why it was changed?

    • GlobalScope is a delicate API and should be used with caution. As the Store can be created in many places in the app and be limited to the feature scope as well, what most likely will happen more often than attaching it to the application lifecycle, using GlobalScope should be very explicit from the client side.
    enhancement 
    opened by zalewskise 0
  • [Enhancement] Remove Identifier interface entirely

    [Enhancement] Remove Identifier interface entirely

    What's in this PR?

    After release CoRed to early adopter, it turns out that we have received an interesting feedback and the usage of the string for "Action" as a key is error-prone and cumbersome. While I partly agree with the feedback, it is indeed worth a shot of improvement.

    Initially, we didn't think this is possible. But it looks like we didn't go deep enough.

    We have spent quite good numbers of hours to understand what the best way is to make compiler reducer the type. It turns out that it is possible with a simple use-site variance projections (out keyword) (KClass<out Any>).

    With this approach, we can basically using KClass as a key in a map while maintaining the type in the StoreAdapter reducerMap and middlewareMap.

    The magic is we can carry over with a KClass<out Any> to describe as a key and pull out the associated value (reducer object and middleware object) correctly so we still maintain the functionality of the StoreAdapter and getting rid the hack (usage of the String as a Key)

    PS. Fun fact, I found out an interesting compiler behavior;

    Screen Shot 2021-07-15 at 23 46 17
    opened by kittinunf 0
Releases(0.7.2)
Owner
Kittinun Vantasin
Android/iOS Enthusiast
Kittinun Vantasin
Image loading for Android backed by Kotlin Coroutines.

An image loading library for Android backed by Kotlin Coroutines. Coil is: Fast: Coil performs a number of optimizations including memory and disk cac

Coil 8.8k Jan 7, 2023
Compose Multiplatform integration for Redux-Kotlin

Redux-Kotlin-Compose Compose Multiplatform integration for Redux Kotlin Installation Artifacts are hosted on maven central. For multiplatform, add the

Redux-Kotlin 7 Sep 7, 2022
Real life Kotlin Multiplatform project with an iOS application developed in Swift with SwiftUI, an Android application developed in Kotlin with Jetpack Compose and a backed in Kotlin hosted on AppEngine.

Conferences4Hall Real life Kotlin Multiplatform project with an iOS application developed in Swift with SwiftUI, an Android application developed in K

Gérard Paligot 98 Dec 15, 2022
A set of highly-opinionated, batteries-included gradle plugins to get you started building delicious multi-module Kotlin projects

Sourdough Gradle What is Sourdough Gradle? Sourdough is a set of highly opinionated gradle plugins that aim to act as the starter for your Kotlin proj

Backbone 0 Oct 3, 2022
Schedule-4-me is an opinionated to-do app to bring chaos to your life.

Schedule-4-me Have you ever had too much control in your life? Ever find yourself stuck at home repeating the same motions over and over again? Well f

null 4 Jan 16, 2022
🍭 GithubSearchKMM - Github Repos Search - Android - iOS - Kotlin Multiplatform Mobile using Jetpack Compose, SwiftUI, FlowRedux, Coroutines Flow, Dagger Hilt, Koin Dependency Injection, shared KMP ViewModel, Clean Architecture

GithubSearchKMM Github Repos Search - Kotlin Multiplatform Mobile using Jetpack Compose, SwiftUI, FlowRedux, Coroutines Flow, Dagger Hilt, Koin Depend

Petrus Nguyễn Thái Học 50 Jan 7, 2023
Kotlin Multiplatform Mobile + Mobile Declarative UI Framework (Jetpack Compose and SwiftUI)

Kotlin Multiplatform Mobile + Mobile Declarative UI Framework (Jetpack Compose and SwiftUI)

Kotchaphan Muangsan 3 Nov 15, 2022
KMM RSS Reader: an open-source, mobile, cross-platform application built with Kotlin Multiplatform Mobile.

KMM RSS Reader This is an open-source, mobile, cross-platform application built with Kotlin Multiplatform Mobile. It's a simple RSS reader, and you ca

Kotlin 1.4k Jan 4, 2023
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

IceRock Development 32 Aug 26, 2022
A tiny Kotlin multiplatform library that assists in saving and restoring objects to and from disk using kotlinx.coroutines, kotlinx.serialisation and okio

Store A tiny Kotlin multiplatform library that assists in saving and restoring objects to and from disk using kotlinx.coroutines, kotlinx.serialisatio

Isuru Rajapakse 98 Jan 3, 2023