Giter Site home page Giter Site logo

reactivecocoa / loop Goto Github PK

View Code? Open in Web Editor NEW
74.0 9.0 8.0 869 KB

Composable unidirectional data flow with ReactiveSwift.

License: Other

Swift 96.95% Ruby 1.22% Shell 1.83%
swift reactiveswift unidirectional-data-flow swiftui reactivecocoa rac ios

loop's Introduction

Unidirectional Reactive Architecture. This is a ReactiveSwift counterpart of RxFeedback.

Documentation

Motivation

Requirements for iOS apps have become huge. Our code has to manage a lot of state e.g. server responses, cached data, UI state, routing etc. Some may say that Reactive Programming can help us a lot but, in the wrong hands, it can do even more harm to your code base.

The goal of this library is to provide a simple and intuitive approach to designing reactive state machines.

Core Concepts

State

State is the single source of truth. It represents a state of your system and is usually a plain Swift type (which doesn't contain any ReactiveSwift primitives). Your state is immutable. The only way to transition from one State to another is to emit an Event.

struct Results<T: JSONSerializable> {
    let page: Int
    let totalResults: Int
    let totalPages: Int
    let results: [T]

    static func empty() -> Results<T> {
        return Results<T>(page: 0, totalResults: 0, totalPages: 0, results: [])
    }
}

struct Context {
    var batch: Results<Movie>
    var movies: [Movie]

    static var empty: Context {
        return Context(batch: Results.empty(), movies: [])
    }
}

enum State {
    case initial
    case paging(context: Context)
    case loadedPage(context: Context)
    case refreshing(context: Context)
    case refreshed(context: Context)
    case error(error: NSError, context: Context)
    case retry(context: Context)
}
Event

Represents all possible events that can happen in your system which can cause a transition to a new State.

enum Event {
    case startLoadingNextPage
    case response(Results<Movie>)
    case failed(NSError)
    case retry
}
Reducer

A Reducer is a pure function with a signature of (State, Event) -> State. While Event represents an action that results in a State change, it's actually not what causes the change. An Event is just that, a representation of the intention to transition from one state to another. What actually causes the State to change, the embodiment of the corresponding Event, is a Reducer. A Reducer is the only place where a State can be changed.

static func reduce(state: State, event: Event) -> State {
    switch event {
    case .startLoadingNextPage:
        return .paging(context: state.context)
    case .response(let batch):
        var copy = state.context
        copy.batch = batch
        copy.movies += batch.results
        return .loadedPage(context: copy)
    case .failed(let error):
        return .error(error: error, context: state.context)
    case .retry:
        return .retry(context: state.context)
    }
}
Feedback

While State represents where the system is at a given time, Event represents a trigger for state change, and a Reducer is the pure function that changes the state depending on current state and type of event received, there is not as of yet any type to emit events given a particular current state. That's the job of the Feedback. It's essentially a "processing engine", listening to changes in the current State and emitting the corresponding next events to take place. It's represented by a pure function with a signature of Signal<State, NoError> -> Signal<Event, NoError>. Feedbacks don't directly mutate states. Instead, they only emit events which then cause states to change in reducers.

public struct Feedback<State, Event> {
    public let events: (Scheduler, Signal<State, NoError>) -> Signal<Event, NoError>
}

func loadNextFeedback(for nearBottomSignal: Signal<Void, NoError>) -> Feedback<State, Event> {
    return Feedback(predicate: { !$0.paging }) { _ in
        return nearBottomSignal
            .map { Event.startLoadingNextPage }
        }
}

func pagingFeedback() -> Feedback<State, Event> {
    return Feedback<State, Event>(skippingRepeated: { $0.nextPage }) { (nextPage) -> SignalProducer<Event, NoError> in
        return URLSession.shared.fetchMovies(page: nextPage)
            .map(Event.response)
            .flatMapError { (error) -> SignalProducer<Event, NoError> in
                return SignalProducer(value: Event.failed(error))
            }
        }
}

func retryFeedback(for retrySignal: Signal<Void, NoError>) -> Feedback<State, Event> {
    return Feedback<State, Event>(skippingRepeated: { $0.lastError }) { _ -> Signal<Event, NoError> in
        return retrySignal.map { Event.retry }
    }
}

func retryPagingFeedback() -> Feedback<State, Event> {
    return Feedback<State, Event>(skippingRepeated: { $0.retryPage }) { (nextPage) -> SignalProducer<Event, NoError> in
        return URLSession.shared.fetchMovies(page: nextPage)
            .map(Event.response)
            .flatMapError { (error) -> SignalProducer<Event, NoError> in
                return SignalProducer(value: Event.failed(error))
            }
        }
}

The Flow

  1. As you can see from the diagram above we always start with an initial state.
  2. Every change to the State will be then delivered to all Feedback loops that were added to the system.
  3. Feedback then decides whether any action should be performed with a subset of the State (e.g calling API, observe UI events) by dispatching an Event, or ignoring it by returning SignalProducer.empty.
  4. Dispatched Event then goes to the Reducer which applies it and returns a new value of the State.
  5. And then cycle starts all over (see 2).
Example
let increment = Feedback<Int, Event> { _ in
    return self.plusButton.reactive
        .controlEvents(.touchUpInside)
        .map { _ in Event.increment }
}

let decrement = Feedback<Int, Event> { _ in
    return self.minusButton.reactive
        .controlEvents(.touchUpInside)
        .map { _ in Event.decrement }
}

let system = SignalProducer<Int, NoError>.system(initial: 0,
    reduce: { (count, event) -> Int in
        switch event {
        case .increment:
            return count + 1
        case .decrement:
            return count - 1
        }
    },
    feedbacks: [increment, decrement])

label.reactive.text <~ system.map(String.init)

Advantages

TODO

Acknowledgements

This is a community fork of the ReactiveFeedback project (with the MIT license) from Babylon Health.

loop's People

Contributors

andersio avatar chitrakotwani avatar daniel1of1 avatar dmcrodrigues avatar freak4pc avatar ilyapuchka avatar konrad-em avatar mluisbrown avatar ole avatar p4checo avatar ruiaaperes avatar sergdort avatar zzcgumn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

loop's Issues

Add events to the feedbacks

Resurrecting old proposal from @inamiy babylonhealth/ReactiveFeedback#41

This is an additive change to add Optional<Event> argument in Feedback so that unnecessary intermediate states will no longer be required.

Event-driven feedback will be useful for following scenarios, without needing to add a new state and then transit (and transit back again):

  • Logging
  • Analytics
  • Routing
  • Image loader (but not managing its internal states)

This is a change from Moore model to (kind of) Mealy model as discussed in babylonhealth/ReactiveFeedback#32 (review) .

Please note that reducer and feedback are still in sequence, not parallel.

Also, please note that Optional<Event> is used here as a workaround since it requires more breaking changes to minimize into non-optional Event.

Remove Old Feedback signature in favour of new.

At this point I do not see a value having two sightly different implementation of the same thing.

I proposing to remove old system operator that takes scheduler in favour of new queue-drain event processing.

FeedbackLoop.Feedback -> Feedback

SwiftUI integration

Loop may offer in-built SwiftUI integration on Apple platforms without creating an extra "LoopUI" package.

Loop only needs to provide standard data funnels to connect feedback loops with SwiftUI, and has no involvement in UI concerns except for the two characters in import SwiftUI. Everything else is SwiftUI's declarative UI realm (data to virtual DOM, vDOM to native view, etc). That is in contrast to our UIKit sibling ReactiveCocoa, which is a heavy UI-focused library that (1) attempted to solve AppKit/UIKit reactive programming at a micro level (KVO-like property bindings), and (2) wraps parts of Objective-C dynamism into friendly Swift APIs.

Since SwiftUI is shipped with the system, no friction is incurred for dependency management on users' end. All these collectively makes it perfect for Loop to offer straightly the said utilities.

Such integration should be excluded from Linux builds.

Concepts

Concepts are built upon the implicit behavior of DynamicProperty, which serves as a clue for SwiftUI runtime to look inside the property wrapper, so as to pick up embedded special wrappers like @State, @ObservedObject and @Environment.

This enables us to build custom property wrappers that provide simple dev experience, while hiding the heavy lifting of bridging feedback loops to SwiftUI world.

Direct state binding like @ObservedObject:

Bound view pseudo code
typealias WeatherStore = Store<WeatherState, WeatherAction>

struct WeatherView: View {
    @WeatherStore.Binding
    var state: WeatherState

    init(store: WeatherStore) {
      _state = store.binding()
    }

    var body: some Body {
        VStack {
            Spacer()

            Text("Current temperature: \(state.temperature)")
                + Text(" \(state.unit)").font(.system(size: 10.0)).baselineOffset(7.0)
            Spacer()
            Button()
                action: { self.$state.perform(.refresh) }
                label: { Text("Refresh ๐Ÿ”„") }

            Spacer()
    }
}

SwiftUI environment injected state bindings

Note: Unlike @State and @ObservedObject, it hasn't been tested whether @EnvironmentObject would work.

Bound view pseudo code
typealias WeatherStore = Store<WeatherState, WeatherAction>

struct WeatherView: View {
    @WeatherStore.EnvironmentBinding
    var state: WeatherStore.State

    var body: some Body {
        VStack {
            Spacer()

            Text("Current temperature: \(state.temperature)")
                + Text(" \(state.unit)").font(.system(size: 10.0)).baselineOffset(7.0)
            Spacer()
            Button()
                action: { self.$state.perform(.refresh) }
                label: { Text("Refresh ๐Ÿ”„") }

            Spacer()
    }
}
Parent view pseudo code
typealias WeatherStore = Store<WeatherState, WeatherAction>
let weatherStore = WeatherStore()

struct ContentView: View {
    var body: some Body {
        WeatherView()
            .environmentObject(weatherStore)
    }
}

Partial store

Already supported via Store.view(value:event:). e.g. injecting via @EnvironmentBinding a partial store that exposes only state & events related to radar images.

typealias WeatherStore = Store<WeatherState, WeatherAction>
let weatherStore = WeatherStore()

struct ContentView: View {
    var body: some Body {
        RadarView()
            .environmentObject(
                weatherStore.view
                    value: \WeatherState.radarImages
                    event: WeatherAction.radar
            )
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.