🐌 snail - An observables framework for Swift

Overview

🐌 snail Carthage compatible Cocoapods codecov.io SwiftPM Compatible

SNAIL

A lightweight observables framework, also available in Kotlin

Installation

Carthage

You can install Carthage with Homebrew using the following command:

brew update
brew install carthage

To integrate Snail into your Xcode project using Carthage, specify it in your Cartfile where "x.x.x" is the current release:

github "UrbanCompass/Snail" "x.x.x"

Swift Package Manager

To install using Swift Package Manager have your Swift package set up, and add Snail as a dependency to your Package.swift.

dependencies: [
    .Package(url: "https://github.com/UrbanCompass/Snail.git", majorVersion: 0)
]

Manually

Add all the files from Snail/Snail to your project

Developing Locally

  1. Run the setup script to install required dependencies ./scripts/setup.sh

Creating Observables

let observable = Observable<thing>()

Disposer

A disposer is in charge of removing all the subscriptions. A disposer is usually located in a centralized place where most of the subscriptions happen (ie: UIViewController in an MVVM architecture). Since most of the subscriptions are to different observables, and those observables are tied to type, all the things that are going to be disposed need to comform to Disposable.

If the Disposer helps get rid of the closures and prevent retention cycles (see weak self section). For the sake of all the examples, let's have a disposer created:

let disposer = Disposer()

Closure Wrapper

The main usage for the Disposer is to get rid of subscription closures that we create on Observables, but the other usage that we found handy, is the ability to dispose of regular closures. As part of the library, we created a small Closure wrapper class that complies with Disposable. This way you can wrap simple closures to be disposed.

let closureCall = Closure {
    print("We ❤️ Snail")
}.add(to: Disposer)

Please note that this would not dispose of the closureCall reference to closure, it would only Dispose the content of the Closure.

Subscribing to Observables

observable.subscribe(
    onNext: { thing in ... }, // do something with thing
    onError: { error in ... }, // do something with error
    onDone: { ... } //do something when it's done
).add(to: disposer)

Closures are optional too...

observable.subscribe(
    onNext: { thing in ... } // do something with thing
).add(to: disposer)
observable.subscribe(
    onError: { error in ... } // do something with error
).add(to: disposer)

Creating Observables Variables

let variable = Variable<whatever>(some initial value)
let optionalString = Variable<String?>(nil)
optionalString.asObservable().subscribe(
    onNext: { string in ... } // do something with value changes
).add(to: disposer)

optionalString.value = "something"
let int = Variable<Int>(12)
int.asObservable().subscribe(
    onNext: { int in ... } // do something with value changes
).add(to: disposer)

int.value = 42

Combining Observable Variables

let isLoaderAnimating = Variable<Bool>(false)
isLoaderAnimating.bind(to: viewModel.isLoading) // forward changes from one Variable to another

viewModel.isLoading = true
print(isLoaderAnimating.value) // true
Observable.merge([userCreated, userUpdated]).subscribe(
  onNext: { user in ... } // do something with the latest value that got updated
}).add(to: disposer)

userCreated.value = User(name: "Russell") // triggers 
userUpdated.value = User(name: "Lee") // triggers 
Observable.combineLatest((isMapLoading, isListLoading)).subscribe(
  onNext: { isMapLoading, isListLoading in ... } // do something when both values are set, every time one gets updated
}).add(to: disposer)

isMapLoading.value = true
isListLoading.value = true // triggers

Miscellaneous Observables

let just = Just(1) // always returns the initial value (1 in this case)

enum TestError: Error {
  case test
}
let failure = Fail(TestError.test) // always fail with error

let n = 5
let replay = Replay(n) // replays the last N events when a new observer subscribes

Operators

Snail provides some basic operators in order to transform and operate on observables.

  • map: This operator allows to map the value of an obsverable into another value. Similar to map on Collection types.

    subject emits `String` whenever `observable` emits. ">
    let observable = Observable<Int>()
    let subject = observable.map { "Number: \($0)" }
    // -> subject emits `String` whenever `observable` emits.
  • filter: This operator allows filtering out certain values from the observable chain. Similar to filter on Collection types. You simply return true if the value should be emitted and false to filter it out.

    let observable = Observable<Int>()
    let subject = observable.filter { $0 % 2 == 0 }
    // -> subject will only emit even numbers.
  • flatMap: This operator allows mapping values into other observables, for example you may want to create an observable for a network request when a user tap observable emits.

    let fetchTrigger = Observable<Void>()
    let subject = fetchTrigger.flatMap { Variable(100).asObservable() }
    // -> subject is an `Observable` that is created when `fetchTrigger` emits.

Subscribing to Control Events

let control = UIControl()
control.controlEvent(.touchUpInside).subscribe(
  onNext: { ... }  // do something with thing
).add(to: disposer)

let button = UIButton()
button.tap.subscribe(
  onNext: { ... }  // do something with thing
).add(to: disposer)

Queues

You can specify which queue an observables will be notified on by using .subscribe(queue: ). If you don't specify, then the observable will be notified on the same queue that the observable published on.

There are 3 scenarios:

  1. You don't specify the queue. Your observer will be notified on the same thread as the observable published on.

  2. You specified main queue AND the observable published on the main queue. Your observer will be notified synchronously on the main queue.

  3. You specified a queue. Your observer will be notified async on the specified queue.

Examples

Subscribing on DispatchQueue.main

observable.subscribe(queue: .main,
    onNext: { thing in ... }
).add(to: disposer)

Weak self is optional

You can use [weak self] if you want, but with the introduction of Disposer, retention cycles are destroyed when calling disposer.disposeAll().

One idea would be to call disposer.disposeAll() when you pop a view controller from the navigation stack.

protocol HasDisposer {
    var disposer: Disposer
}

class NavigationController: UINavigationController {
    public override func popViewController(animated: Bool) -> UIViewController? {
        let viewController = super.popViewController(animated: animated)
        (viewController as? HasDisposer).disposer.disposeAll()
        return viewController
    }
}

In Practice

Subscribing to Notifications

NotificationCenter.default.observeEvent(Notification.Name.UIKeyboardWillShow)
  .subscribe(queue: .main, onNext: { notification in
    self.keyboardWillShow(notification)
  }).add(to: disposer)

Subscribing to Gestures

let panGestureRecognizer = UIPanGestureRecognizer()
panGestureRecognizer.asObservable()
  .subscribe(queue: .main, onNext: { sender in
    // Your code here
  }).add(to: disposer)
view.addGestureRecognizer(panGestureRecognizer)

Subscribing to UIBarButton Taps

navigationItem.leftBarButtonItem?.tap
  .subscribe(onNext: {
    self.dismiss(animated: true, completion: nil)
  }).add(to: disposer)
Comments
  • Add swift-tools-version, update gitignore, update Package.swift

    Add swift-tools-version, update gitignore, update Package.swift

    Hey! Hope you guys are doing well :D!

    I was moving a project over to use SPM and noticed a few errors when I added Snail.

    1. Looks like Package.swift must begin with swift-tools-version:. I set the version to 4.2 and 5.2 but I'm happy to change that to whatever you guys want :).

    2. Looks like exclude isn't a parameter in the Package initializer (I'm not sure when that changed)?

      Error with `exclude`

      snail-exclude-error

    3. Added .swiftpm/ to the gitignore as per this

    opened by nkanetka 3
  • Addition Bind Function

    Addition Bind Function

    Description

    We had this discussion some time ago on Slack, regarding adding this helper / convenient function that removes unnecessarily / cumbersome binding code.

    We would replace:

    userService.isRefreshing.asObservable().subscribe(onNext: { [weak self] isRefreshing in
         self?.loadingMap.value = isRefreshing
    })
    

    By this single line:

    loadingMap.bind(to: userService.isRefreshing)
    

    Note: some of the other suggestions that were "not preferred" by the team:

    // Custom operator
    loadingMap <~ userService.isRefreshing
    
    // Static function
    Observable.bind(loadingMap, to: userService.isRefreshing)
    
    // Free function
    bind(loadingMap, to: userService.isRefreshing)
    
    opened by bastienFalcou 3
  • Installation Section

    Installation Section

    Hey, your library is really interesting.

    The only problem I found was the README.md, which lacks an Installation Section I created this iOS Open source Readme Template so you can take a look on how to easily create an Installation Section If you want, I can help you to organize the lib.

    What are your thoughts? 😄

    opened by lfarah 3
  • Update podspce file, change deployment target to ios 8

    Update podspce file, change deployment target to ios 8

    I noticed top closed PR that shows "Don't commit the podspec", but sorry to say our app still supports iOS system earlier than 11, and I see that Snail supports iOS 8+ actally, so could we change deployment target to iOS 8?

    opened by XueshiQiao 2
  • Add map, filter and flatMap operators to Observable

    Add map, filter and flatMap operators to Observable

    This PR aims to add some needed functionality to Snail. As well as cleans up some of the API.

    Currently Observable type doesn't support, mapping, filtering or creating other observables.

    This PR adds:

    • map function to Observable
    • filterfunction to Observable
    • flatMap function to Observable
    • Adds combineLatest for 3 and 4 observables.
    • Adds a timeout option to block function.
    • Tests for the above

    Note:

    • This is a breaking API change to combineLatest since I removed the tuple requirement from the function call.
    • This is a breaking API change to Variable.map since I made transform argument parameter not required.
    opened by luispadron 2
  • Variable Mapping

    Variable Mapping

    I am suggesting this addition to Snail. This allows to map a Unique<T> into a Unique<U> that will receive the same notifications, with the value transformed from its initial type T to the expected new type U.

    This is useful for me here when I use:

    public enum ValidationField {
        case binding(Variable<String?>) // expects a Variable of type <String?>
        // ...
    }
    

    But in my case, I need to bind viewModel.showingAgent which is of type Unique<FullContact?>. I don't want to create a new enumeration member taking that type specifically. I prefer to reuse that existing enumeration member and map viewModel.showingAgent into a Unique<String?>.

    I think this could be useful in multiple places as well along the way 👍

    opened by bastienFalcou 2
  • Add twoWayBind to Variable<T>

    Add twoWayBind to Variable

    Summary

    • Create TwoWayBind protocol
    • Connect two Variable<T>s so that any update to one, updates the other.
    VarA<Int> -----1----------2-------3-------4---------------5-------------------------------->
                    \         |        \       \              |
                     |       /          |       |            /
    VarB<Int> -------1------2-----------3-------4-----------5---------------------------------->
    
    varA.twoWayBind(with: varB)
    
    varA.asObservable().subscribe(onNext: { value in
        print(value) // 1, 2, 3, 4, 5
    }
    varB.asObservable().subscribe(onNext: { value in
        print(value) // 1, 2, 3, 4, 5
    }
    
    opened by jacksoncheek 1
  • Add zip operator

    Add zip operator

    Summary

    • Adding Observable.zip(...) operator, which is very similar to Observable.combineLatest(...)
    • http://reactivex.io/documentation/operators/zip.html
    • The Zip method returns an Observable that applies a function of your choosing to the combination of items emitted, in sequence, by two (or more) other Observables, with the results of this function becoming the items emitted by the returned Observable. It applies this function in strict sequence, so the first item emitted by the new Observable will be the result of the function applied to the first item emitted by Observable #1 and the first item emitted by Observable #2; the second item emitted by the new zip-Observable will be the result of the function applied to the second item emitted by Observable #1 and the second item emitted by Observable #2; and so forth. It will only emit as many items as the number of items emitted by the source Observable that emits the fewest items.
    • Only adding for two observables at this time for simplicity. If we want more (similar to .combineLatest), let's wait for that use case to reduce complexity in the implementations.
    opened by jacksoncheek 1
  • Add thread safety to Observable & Replay

    Add thread safety to Observable & Replay

    Summary

    Both Observable and Replay have issues regarding data races when accessing events and subscribers arrays.

    In this PR we are adding a dedicated queue for accessing these arrays.

    We use sync when reading the values from the array and use async with a barrier (which guarantees to wait for the last access to finish before a new access).

    I've also added two new tests which both previously fail when running with thread sanitizer but pass now with these changes.

    opened by luispadron 1
  • Removed Inheritance for Unique

    Removed Inheritance for Unique

    • Inheritance was causing errors on the requirements for the superclass
    • This PR removes that inheritance since we're dealing with two different types
    • Fixes #136
    opened by lucaslain 1
Releases(0.13.0)
Owner
Compass
Compass Real Estate
Compass
Swift Apps in a Swoosh! A modern framework for creating iOS apps, inspired by Redux.

Katana is a modern Swift framework for writing iOS applications' business logic that are testable and easy to reason about. Katana is strongly inspire

Bending Spoons 2.2k Jan 1, 2023
EventBroadcaster is a lightweight event handler framework, written in swift for iOS, macOS, tvOS & watchOS applications.

EventBroadcaster is a lightweight event handler framework, written in swift for iOS, macOS, tvOS & watchOS applications.

Ali Samaiee 4 Oct 5, 2022
UI event handling using Apple's combine framework.

Description Combinative is a library for UI event handling using Apple's combine framework. It doesn't need many dependencies because it is written ma

noppefoxwolf 106 Jan 29, 2022
Open source implementation of Apple's Combine framework for processing values over time.

OpenCombine Open-source implementation of Apple's Combine framework for processing values over time. The main goal of this project is to provide a com

OpenCombine 2.4k Dec 26, 2022
RxReduce is a lightweight framework that ease the implementation of a state container pattern in a Reactive Programming compliant way.

About Architecture concerns RxReduce Installation The key principles How to use RxReduce Tools and dependencies Travis CI Frameworks Platform Licence

RxSwift Community 125 Jan 29, 2022
SwiftUI-compatible framework for building browser apps with WebAssembly and native apps for other platforms

SwiftUI-compatible framework for building browser apps with WebAssembly At the moment Tokamak implements a very basic subset of SwiftUI. Its DOM rende

TokamakUI 2k Dec 30, 2022
SwiftUI-compatible framework for building browser apps with WebAssembly and native apps for other platforms

SwiftUI-compatible framework for building browser apps with WebAssembly At the moment Tokamak implements a very basic subset of SwiftUI. Its DOM rende

TokamakUI 2k Dec 29, 2022
Write great asynchronous code in Swift using futures and promises

BrightFutures How do you leverage the power of Swift to write great asynchronous code? BrightFutures is our answer. BrightFutures implements proven fu

Thomas Visser 1.9k Dec 20, 2022
Easy Swift Futures & Promises.

❗️ Archived now ❗️ Since Apple released Combine framework, I decide to archive this repo. You still can use this repo as an example of Future/Promise

Dmytro Mishchenko 40 Sep 23, 2022
Type-safe event handling for Swift

emitter-kit v5.2.2 A replacement for NSNotificationCenter#addObserver and NSObject#addObserver that is type-safe and not verbose. import EmitterKit /

Alec Larson 570 Nov 25, 2022
A Swift based Future/Promises Library for IOS and OS X.

FutureKit for Swift A Swift based Future/Promises Library for IOS and OS X. Note - The latest FutureKit is works 3.0 For Swift 2.x compatibility use v

null 759 Dec 2, 2022
📡 Helping you own NotificationCenter in Swift!

Notificationz ?? Helping you own NotificationCenter Highlights Keep Your Naming Conventions: This library gives you convenient access to NotificationC

Kitz 77 Feb 18, 2022
Observable is the easiest way to observe values in Swift.

Observable is the easiest way to observe values in Swift. How to Create an Observable and MutableObservable Using MutableObservable you can create and

Robert-Hein Hooijmans 368 Nov 9, 2022
Modern thread-safe and type-safe key-value observing for Swift and Objective-C

Now Archived and Forked PMKVObserver will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork o

Postmates Inc. 708 Jun 29, 2022
A library for reactive and unidirectional Swift applications

ReactorKit is a framework for a reactive and unidirectional Swift application architecture. This repository introduces the basic concept of ReactorKit

ReactorKit 2.5k Dec 28, 2022
ReSwift is a Redux-like implementation of the unidirectional data flow architecture in Swift.

ReSwift is a Redux-like implementation of the unidirectional data flow architecture in Swift. ReSwift helps you to separate three important concerns of your app's components.

null 7.3k Jan 9, 2023
Lightweight Promises for Swift & Obj-C

Tomorrowland Tomorrowland is an implementation of Promises for Swift and Objective-C. A Promise is a wrapper around an asynchronous task that provides

Lily Ballard 115 Nov 23, 2022
VueFlux is the architecture to manage state with unidirectional data flow for Swift, inspired by Vuex and Flux.

Unidirectional State Management Architecture for Swift - Inspired by Vuex and Flux Introduction VueFlux is the architecture to manage state with unidi

Ryo Aoyama 324 Dec 17, 2022
When is a lightweight implementation of Promises in Swift

Description When is a lightweight implementation of Promises in Swift. It doesn't include any helper functions for iOS and OSX and it's intentional, t

Vadym Markov 259 Dec 29, 2022