• Stars
    star
    153
  • Rank 243,368 (Top 5 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Redux implementation in Swift using RxSwift

RxState RxState: Redux + RxSwift

RxState a predictable state container for Swift apps. It's a tiny library built on top of RxSwift and inspired by Redux that facilitates building Unidirectional Data Flow architecture.

Why Unidirectional Data Flow Architecture?

  1. Helps you manage state in a consistent and unified way that guaranty itโ€™s always predictable (After all, state is the source of all evil and you wanna keep that evil in check).
  2. Limits the way app state can be mutated, which makes your app easier to understand.
  3. Makes your code easy to test.
  4. Enables faster debugging.
  5. Itโ€™s is entirely platform independent - you can easily use the same business logic and share it between apps for multiple platforms (iOS, tvOS, etc.).

Architecture Components

  • App State: A single immutable data structure. It includes the UI state, the navigation state and the state of your model layer.

  • Store:Contains the app state and notifies the App State Observers of the App State updates.

  • Reducer: A pure function that takes the current app state and an Action as input, creates a new App State that reflects the changes described by the Action, and returns the new App State.

  • Action: Actions describe a state change. The only way to modified the App State is by dispatching Actions to the Store.

  • Action Creators and Dispatchers: Creates Actions and dispatch them to the store.

  • App State Observers: Observers the App State in the Store to transform it to presentable data, write logs, etc.

  • View: Presents the presentable data that was deriver from the App State and delivers the user's interactions to the Action Creators and Dispatchers.

How it works?

  1. The View/View Controller sends events (The View Model's inputs) to the View Model.

  2. The View Model creates an Action from the received inputs and dispatch them to the Store.

  • The View Model can use a dedicated Action Creators to create Actions. Action Creators do can async work and, based on the results it gets, returns different Actions to the View Model to dispatch.
  1. The Store sends the App State and the received Action to the Reducer.

  2. The Reducer receives the current App State and the dispatched Action, computes and returns new App State.

  3. The Store sends the new App State to the subscribers.

  • One of the subscribers could be a Middleware that logs the App State resulted from dispatching an Action.
  1. The View Model receives the new App State, transform it presentable data, and send it to the View/View Controller.
  • The View Model can use Transformers to transform the App State to presentable data. This helps you reuse the transformation code in different View Models.
  1. The View/View Controller render the UI to show the presentable data to the user.

How does RxState helps you build the Architecture?

RxState defines the main component for you:

  1. Store: Contains the App State in the form of Driver<[SubstateType]>.

  2. SubstateType: A protocol that tags structs representing a substate. Ex.

struct TasksState: SubstateType {   
    var tasks: [Task]
    var addingTask: Bool
}

You can add a Substates to the App State by dispatching StoreAction.add(states: [SubstateType]).

let tasksState = TasksState()
let action = StoreAction.add(states: [tasksState])
store.dispatch(action: action)
  1. ActionType: A protocol that tags an Action. The Store has the following Actions:
public enum StoreAction: ActionType {
    /// Adds substates to the application state.
    case add(states: [SubstateType])

    /// Removes all substates in the application state.
    case reset
}
  1. MainReducer: A reducer used by the Store's dispatch function to call the respective reducer based on the Action type.
let mainReducer: MainReducer = { (state: [SubstateType], action: ActionType) -> [SubstateType] in
    // Copy the `App State`
    var state: [SubstateType] = state
    
    // Cast to a specific `Action`.
    switch action {
    case let action as TasksAction:

        // Extract the `Substate`.
        guard var (tasksStateIndex, tasksState) = state
            .enumerated()
            .first(where: { (_, substate: SubstateType) -> Bool in
                return substate is Store.TasksState}
            ) as? (Int, Store.TasksState)
            else {
                fatalError("You need to register `TasksState` first")
        }

        // Reduce the `Substate` to get a new `Substate`.
        tasksState = Store.reduce(state: tasksState, action: action)
    
        // Replace the `Substate` in the `App State` with the new `Substate`.
        state[tasksStateIndex] = tasksState as SubstateType
    
    default:
        fatalError("Unknown action type")
    }
    
    // Return the new `App State`
    return state
}
  1. MiddlewareType: A protocol defining an object that can observe the App State and the last dispatched Action and does something with it like logging:
protocol LoggingMiddlewareType: Middleware, HasDisposeBag {}

final class LoggingMiddleware: LoggingMiddlewareType {
    var disposeBag = DisposeBag()

    func observe(currentStateLastAction: Driver<CurrentStateLastAction>) {
        currentStateLastAction
            .drive(
                onNext: { (currentState: [SubstateType], lastAction: ActionType?) in
                    print(currentState)
                    print(lastAction)
                }, onCompleted: nil, onDisposed: nil)
            .disposed(by: disposeBag)
        }
    }
}

Dependencies

Requirements

  • Swift 5

Installation

pod 'RxState'

Create a Package.Swift file in your project's root folder.

Add following content into the Package.swift file

// swift-tools-version:5.0

import PackageDescription

let package = Package(
  name: "YourProjectName",
  dependencies: [
    .package(url: "https://github.com/RxSwiftCommunity/RxState.git", from: "0.6.0")
  ],
  targets: [
    .target(name: "YourProjectTarget", dependencies: ["RxState"])
  ]
)

Demo

I have tried to make the demo app as comprehensive as possible. It currently runs on iOS and macOS. Notice how, because of the architecture, only the View/ View Controller layer needed to change in order to port the app from iOS to macOS.

Contributing

We would love to see you involved! Feedback and contribution are greatly appreciated :) Checkout the Contributing Guide and the Code of Conduct.

Influences and credits

  • RxSwift: Reactive Programming in Swift.
  • Redux: a predictable state container for JavaScript apps.

Author

Nazih Shoura, [email protected]

License

This library belongs to RxSwiftCommunity.

RxState is available under the MIT license. See the LICENSE file for more info.

More Repositories

1

RxDataSources

UITableView and UICollectionView Data Sources for RxSwift (sections, animated updates, editing ...)
Swift
3,054
star
2

RxFlow

RxFlow is a navigation framework for iOS applications based on a Reactive Flow Coordinator pattern
Swift
1,872
star
3

RxAlamofire

RxSwift wrapper around the elegant HTTP networking in Swift Alamofire
Swift
1,612
star
4

RxKeyboard

Reactive Keyboard in iOS
Swift
1,533
star
5

RxGesture

RxSwift reactive wrapper for view gestures
Swift
1,369
star
6

RxSwiftExt

A collection of Rx operators & tools not found in the core RxSwift distribution
Swift
1,317
star
7

RxRealm

RxSwift extension for RealmSwift's types
Swift
1,153
star
8

Action

Abstracts actions to be performed in RxSwift.
Swift
875
star
9

RxOptional

RxSwift extensions for Swift optionals and "Occupiable" types
Swift
701
star
10

RxAnimated

Animated RxCocoa bindings
Swift
686
star
11

NSObject-Rx

Handy RxSwift extensions on NSObject, including rx.disposeBag.
Swift
640
star
12

RxMarbles

RxMarbles iOS app
Swift
482
star
13

RxViewModel

ReactiveViewModel-esque using RxSwift
Swift
401
star
14

RxTheme

Theme management based on Rx
Swift
381
star
15

RxReachability

RxSwift bindings for Reachability
Swift
283
star
16

RxNimble

Nimble extensions making unit testing with RxSwift easier ๐ŸŽ‰
Swift
265
star
17

RxWebKit

RxWebKit is a RxSwift wrapper for WebKit
Swift
248
star
18

RxFirebase

RxSwift extensions for Firebase
Swift
224
star
19

RxKingfisher

Reactive extension for the Kingfisher image downloading and caching library
Swift
223
star
20

RxGRDB

Reactive extensions for SQLite
Swift
218
star
21

RxSwiftUtilities

Helpful classes and extensions for RxSwift
Swift
189
star
22

RxCoreLocation

RxCoreLocation is a reactive abstraction to manage Core Location.
Swift
181
star
23

RxMediaPicker

A reactive wrapper built around UIImagePickerController.
Swift
179
star
24

RxCoreData

RxSwift extensions for Core Data
C
164
star
25

RxRealmDataSources

An easy way to bind an RxRealm observable to a table or collection view
Swift
161
star
26

RxStarscream

A lightweight extension to subscribe Starscream websocket events with RxSwift
Swift
152
star
27

RxVisualDebugger

WIP! Very quick and very dirty test for a visual Rx debugger
JavaScript
142
star
28

RxLocalizer

RxLocalizer allows you to localize your apps, using RxSwift ๐Ÿš€
Swift
134
star
29

RxBiBinding

Reactive two-way binding
Swift
126
star
30

RxReduce

RxReduce is a lightweight framework that ease the implementation of a state container pattern in a Reactive Programming compliant way.
Swift
125
star
31

RxMKMapView

RxMKMapView is a RxSwift wrapper for MKMapView `delegate`.
Swift
121
star
32

RxASDataSources

RxDataSource for AsyncDisplayKit/Texture
Swift
119
star
33

RxCocoa-Texture

RxCocoa Extension Library for Texture.
Swift
100
star
34

RxGoogleMaps

RxSwift reactive wrapper for GoogleMaps SDK
Swift
95
star
35

RxSegue

Swift
80
star
36

FirebaseRxSwiftExtensions

Extension Methods for Firebase and RxSwift
Swift
77
star
37

RxMultipeer

A testable RxSwift wrapper around MultipeerConnectivity
Swift
69
star
38

RxIGListKit

RxSwift wrapper for IGListKit
Swift
62
star
39

RxBinding

Simple data binding operators ~> and <~> for RxSwift.
Swift
62
star
40

RxPager

Pager for RxSwift
Swift
60
star
41

RxCoreMotion

Provides an easy and straight-forward way to use Apple iOS CoreMotion responses as Rx Observables.
Swift
60
star
42

RxFileMonitor

RxSwift wrapper around CoreFoundation file events (FSEvent*)
Swift
60
star
43

RxFirebase-Deprecated

Implement RxSwift with the new Firebase
Swift
54
star
44

RxAlert

Swift
50
star
45

RxSnippets

Several snippets for work with RxSwift
50
star
46

RxCookbook

Community driven RxSwift cookbook ๐Ÿด๐Ÿ“š
50
star
47

rxswiftcommunity.github.io

For projects that support RxSwift
Ruby
50
star
48

RxController

A library for developing iOS app with MVVM-C based on RxFlow and RxSwift.
Swift
42
star
49

RxHttpClient

Simple Http client (Use RxSwift for stream data)
Swift
39
star
50

RxEventHub

`RxEventHub` makes multicasting event easy, type-safe and error-free, use it instead of `NSNotificationCenter` now!
Swift
36
star
51

RxModal

Subscribe to your modal flows
Swift
28
star
52

RxBatteryManager

A Reactive BatteryManager in Swift for iOS
Swift
24
star
53

RxAlertViewable

A simple alert library with RxSwift MVVM supported.
Swift
20
star
54

contributors

Guidelines for contributing to the RxSwiftCommunity, and a good place to raise questions.
20
star
55

guides.rxswift.org

Content of the website guides.rxswift.org
HTML
19
star
56

RxAVFoundation

RxAVFoundation (based on RxSwift)
Swift
17
star
57

RxTask

An RxSwift implementation of a command line runner.
Swift
15
star
58

RxContacts

RxContacts is a RxSwift wrapper around the Contacts Framework.
Swift
13
star
59

RxTestExt

A collection of operators & tools not found in the core RxTest distribution
Swift
13
star
60

RxVision

RxVision (based on RxSwift)
Swift
13
star
61

RxCoreNFC

RxCoreNFC (based on RxSwift)
Swift
11
star
62

RxCloudKit

RxCloudKit (based on RxSwift)
Swift
9
star
63

RxARKit

RxARKit (based on RxSwift)
Swift
9
star
64

RxTapAction

Reactive extensions for adding tap action gesture to UIView or UICollectionView.
Swift
9
star
65

RxSceneKit

RxSceneKit (based on RxSwift)
Swift
5
star
66

SimplestDemostrationOfUsingOperator

Simplest way to show how `using` operator works.
Swift
5
star
67

Docs

RxSwift Official Docs - Generated by Jazzy
HTML
5
star
68

RxSocket.io

Rx wrapper over socket.io library with Generic functions
Swift
5
star
69

RxSpriteKit

RxSpriteKit (based on RxSwift)
Swift
4
star
70

RxOnDemandResources

RxOnDemandResources (based on RxSwift)
Swift
4
star
71

FakeRepo

This is a temporary fake repo, please ignore it :)
Swift
2
star
72

peril

Settings for the RxSwiftCommunity organization's Peril server
TypeScript
2
star