Swiftpack.co - ReactiveCocoa/Loop as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by ReactiveCocoa.
ReactiveCocoa/Loop 2.0.0
Composable unidirectional data flow with ReactiveSwift.
⭐️ 60
🕓 1 year ago
.package(url: "https://github.com/ReactiveCocoa/Loop.git", from: "2.0.0")

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



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 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)

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

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)

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)
            .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)
            .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).
let increment = Feedback<Int, Event> { _ in
    return self.plusButton.reactive
        .map { _ in Event.increment }

let decrement = Feedback<Int, Event> { _ in
    return self.minusButton.reactive
        .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)




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


Stars: 60
Last commit: 3 weeks ago
jonrohan Something's broken? Yell at me @ptrpavlik. Praise and feedback (and money) is also welcome.


Release Notes

1 year ago

This is the first stable release of Loop 2.0. It requires Swift 5.2, and supports CocoaPods, Carthage and Swift Package Manager (tools version 5.2).

API consolidation

Introduce Loop, a thread-safe implementation as the source of truth for your unidirectional data flows.

It is renamed from the v1.0 FeedbackLoop, and merged with features from the experimental compositional Store. Note that Loop now starts as it is initialised — start() and stop() previously provided by FeedbackLoop are now no-op and are officially deprecated.

API changes

New feedback variants

Loop now provides two new feedback variants:

  • whenBecomesTrue(_:effects:)

    Given a predicate over the loop state, it spawns an effect with a snapshot of the state, when a positive edge is observed from the the predicate output. It automatically cancels any outstanding effect if a negative edge is observed.

  • firstValueAfterNil(_:effects:)

    Given a transform over the loop state, it spawns an effect with the first non-nil value from the transform output. It automatically cancels any outstanding effect if any nil is observed.

Deprecated feedback variants

The aforementioned feedback variants are intended to replace predicate: as a standard offering in Loop.

We believe that the new variants provide more specialised semantics for the purpose of application development. Most importantly, from the production experience of Loop observed, we are confident that these are more flexible defaults to adapt to the variety in state modelling complexity (e.g., from sum type FSM, to product of sums).

Scoped loops

You can now create scoped loops through Loop.scoped to create lens of your root loop for injecting into different areas of your application.

Note on the scheduler-bound loop API

The scheduler-bound loop API — instantiated via Property.init or SignalProducer.system — has been deprecated since Loop 1.0. They may be removed in the next major release.

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics