NotificationCenter based Lightweight UI / AnyObject binder.

Related tags

EventBus Continuum
Overview

Continuum

CI Status Version Carthage compatible License Platform

NotificationCenter based Lightweight UI / AnyObject binder.

final class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    private let viewModel: ViewModel = ViewModel()
    private let center = NotificationCenter()
    private let bag = ContinuumBag()

    override func viewDidLoad() {
        super.viewDidLoad()

        center.continuum
            .observe(viewModel.text, on: .main, bindTo: label, \.text)
            .disposed(by: bag)

        viewModel.text.value = "Binding this text to label.text!"
    }
}

final class ViewModel {
    let text: Variable<String>

    init() {
        self.text = Variable(value: "")
    }
}

Usage

1. Observe object KeyPath and bind it to target KeyPath

NotificationCenter's instance has continuum property. You can access Continuum functions from it.

let center = NotificationCenter()
let observer = center.continuum.observe(viewModel, \.text, on: .main, bindTo: label, \.text)

Above source code means observe viewModel's text propety and bind that value to label's text property on main thread. If property is observed, current value comes immediately.

Notify changes with func post(keyPath:)

If value changed, notify changes like this.

viewModel.text = "Changed"
center.continuum.post(keyPath: \ViewModel.text)
print(label.text) // Changed

2. Observe Constant / Variable and bind it to target KeyPath

Constant / Variable are value wrapper. Variable has getter / setter. Constant has only getter.

let center = NotificationCenter()
let text = Variable<String>(value: "")
let observer = center.continuum.observe(text, on: .main, bindTo: label, \.text)

If property is observed, current value comes immediately.

3. Observe Constant / Variable and bind it to closure

Constant / Variable are value wrapper. Variable has getter / setter. Constant has only getter.

let center = NotificationCenter()
let text = Variable<String>(value: "")
let observer = center.continuum.observe(text, on: .main, onValueChange: { value in
    // something to do
})

If property is observed, current value comes immediately.

Notify changes with setter of value at Variable

If Variable's value is changed, func post(name:object:) is automatically executed.

text.value = "Changed"
print(label.text) // Changed

In addition, if Variable's value is changed, related Constant value is automatically changed.

let center = NotificationCenter()
let variable = Variable<String>(value: "")
let constant = Constant<String>(variable: variable)
let observer = center.continuum.observe(constant, on: .main, bindTo: label, \.text)
variable.value = "Changed"
print(label.text) // Changed

Lifecycle of ContinuumObserver

func observe(_:,_:,on:,bindTo:,_:) returns ContinuumObserver. If func cancel() of ContinuumObserver called, observation is cancelled.

let observer = center.continuum.observe(viewModel, \.text, on: .main, bindTo: label, \.text)
observer.cancel()

If adding observer to ContinumeBag, observation is cancelled by lifecycle of ContinumeBag.

var bag = ContinumeBag()
center.continuum
    .observe(viewModel, \.text, on: .main, bindTo: label, \.text)
    .disposed(by: bag)

bag = ContinumeBag() // previous instance of ContinumeBag is released and observation is cancelled.

Example

Playground

You can try Continuum with Playground. Open Continuum.xcworkspace and run build. You can try like this.

Example Project

To run the example project, clone the repo, and run pod install from the Example directory first. Open ContinuumSample.xcworkspace and run build. You can try a simple counter app like this.

Requirements

  • Xcode 9.2 or later
  • Swift 4.0.3 or later
  • iOS 10.0 or later

Installation

CocoaPods

Continuum is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'Continuum'

Carthage

If you’re using Carthage, simply add Continuum to your Cartfile:

github "marty-suzuki/Continuum"

Author

marty-suzuki, [email protected]

License

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

You might also like...
📡 Helping you own NotificationCenter in Swift!

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

A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety
A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety

A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety. Type Safe No more userInfo dictionary and Downcasting,

NoticeObserveKit is type-safe NotificationCenter wrapper.

NoticeObserveKit NoticeObserveKit is type-safe NotificationCenter wrapper. // .keyboardWillShow is a static property. Notice.Center.default.observe(na

📡 Helping you own NotificationCenter in Swift!

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

Swift UIKit E-Commerce (UgurShopping)  No StoryBoard   Firebase, FireStore, FirebaseAuth, KingFisher, SwiftEntryKit, ProgressHud, Alamofire UICollectionViewCompositionalLayout, NotificationCenter
Swift UIKit E-Commerce (UgurShopping) No StoryBoard Firebase, FireStore, FirebaseAuth, KingFisher, SwiftEntryKit, ProgressHud, Alamofire UICollectionViewCompositionalLayout, NotificationCenter

Swift UIKit E-Commerce (UgurShopping) No StoryBoard Firebase, FireStore, FirebaseAuth, KingFisher, SwiftEntryKit, ProgressHud, Alamofire UICollectionViewCompositionalLayout, NotificationCenter

A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS
A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS

A native, lightweight and secure time-based (TOTP) & counter-based (HOTP) password client built for iOS Built by Tijme Gommers – Buy me a coffee via P

Super lightweight web framework in Swift based on SWSGI

Ambassador Super lightweight web framework in Swift based on SWSGI Features Super lightweight Easy to use, designed for UI automatic testing API mocki

CleanroomLogger provides an extensible Swift-based logging API that is simple, lightweight and performant
CleanroomLogger provides an extensible Swift-based logging API that is simple, lightweight and performant

CleanroomLogger CleanroomLogger provides an extensible Swift-based logging API that is simple, lightweight and performant. The API provided by Cleanro

Super lightweight web framework in Swift based on SWSGI

Ambassador Super lightweight web framework in Swift based on SWSGI Features Super lightweight Easy to use, designed for UI automatic testing API mocki

SwiftySideMenu is a lightweight and easy to use side menu controller to add left menu and center view controllers with scale animation based on Pop framework.
SwiftySideMenu is a lightweight and easy to use side menu controller to add left menu and center view controllers with scale animation based on Pop framework.

SwiftySideMenu SwiftySideMenu is a lightweight, fully customizable, and easy to use controller to add left menu and center view controllers with scale

Lightweight app to view your WoT (BB, Blitz) stats (XVM based)
Lightweight app to view your WoT (BB, Blitz) stats (XVM based)

KTTC Lite Приложение для танкистов, следящих за своей статистикой! Функционал Базовая статистика аккаунта WoT, WoT Blitz Расширенная статистика XVM (W

Simple, block-based, lightweight library over CoreBluetooth. Will clean up your Core Bluetooth related code.
Simple, block-based, lightweight library over CoreBluetooth. Will clean up your Core Bluetooth related code.

LGBluetooth Simple, block-based, lightweight library over CoreBluetooth. Steps to start using Drag and Drop it into your project Import "LGBluetooth.h

🅿️ PandoraPlayer is a lightweight music player for iOS, based on AudioKit and completely written in Swift.
🅿️ PandoraPlayer is a lightweight music player for iOS, based on AudioKit and completely written in Swift.

Made by Applikey Solutions Find this project on Dribbble Table of Contents Purpose Features Supported OS & SDK Versions Installation Usage Demo Releas

A lightweight but powerful network library with simplified and expressive syntax based on AFNetworking.
A lightweight but powerful network library with simplified and expressive syntax based on AFNetworking.

XMNetworking English Document XMNetworking 是一个轻量的、简单易用但功能强大的网络库,基于 AFNetworking 3.0+ 封装。 其中,XM 前缀是我们团队 Xcode-Men 的缩写。 简介 如上图所示,XMNetworking 采用中心化的设计思想

GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in iOS, macOS & tvOS apps.

GCDWebServer is a modern and lightweight GCD based HTTP 1.1 server designed to be embedded in iOS, macOS & tvOS apps. It was written from scr

A clean and lightweight progress HUD based on SVProgressHUD, converted to Swift with the help of Swiftify.

IHProgressHUD IHProgressHUD is a clean and easy-to-use HUD meant to display the progress of an ongoing task on iOS and tvOS. IHProgressHUD is based on

A lightweight Swift date library for parsing, validating, manipulating, and formatting dates based on moment.js.

A lightweight Swift date library for parsing, validating, manipulating, and formatting dates based on moment.js.

Lightweight MetricKit-based diagnostics reporting

MeterReporter Lightweight MetricKit-based diagnostics reporting. MeterReporter will capture MetricKit payloads and relay them to a backend. It uses Me

A lightweight stochastic optimizer based on slime mold (Slime Mold Algorithm)
A lightweight stochastic optimizer based on slime mold (Slime Mold Algorithm)

Slime This is a Swift implementation of a Slime Mold Algorithm - a stochastic optimizer - generally based on this paper The only dependency required b

Comments
  • observe with onValueChange closure

    observe with onValueChange closure

    Added new observe method with a value handler closure. This way user can define simple action trigger like this.

    class ViewModel {
        let alertMessage: Variable<String>
    }
    
    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
    
            center.continuum.observe(viewModel.alertMessage, on: .main) { [weak self] msg in
                if !msg.isEmpty {
                    self?.alert(msg)
                }
            }
        }
    }
    

    Also I added FIXME comment to where initial handler() call isn't dispatched on specified queue.

    opened by toshi0383 1
Owner
Taiki Suzuki
AbemaTV / University of Aizu 18th
Taiki Suzuki
NoticeObserveKit is type-safe NotificationCenter wrapper.

NoticeObserveKit NoticeObserveKit is type-safe NotificationCenter wrapper. // .keyboardWillShow is a static property. Notice.Center.default.observe(na

Taiki Suzuki 147 Nov 24, 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 260 Oct 12, 2022
⚡️ Lightweight full-featured Promises, Async & Await Library in Swift

Lightweight full-featured Promises, Async & Await Library in Swift What's this? Hydra is full-featured lightweight library which allows you to write b

Daniele Margutti 2k Dec 31, 2022
Lightweight promises for iOS, macOS, tvOS, watchOS, and Linux

Futures Futures is a cross-platform framework for simplifying asynchronous programming, written in Swift. It's lightweight, fast, and easy to understa

David Ask 60 Aug 11, 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
A Promise library for Swift, based partially on Javascript's A+ spec

Promise A Promise library for Swift, based partially on Javascript's A+ spec. What is a Promise? A Promise is a way to represent a value that will exi

Soroush Khanlou 622 Nov 23, 2022
'The Particle Binder' - Winning WWDC22 Swift Student Challenge submission!

The Particle Binder 'The Particle Binder' - Winning WWDC22 Swift Student Challenge submission! Welcome to The Particle Binder, the particle accelerato

David 8 Sep 26, 2022
CachyKit - A Caching Library is written in Swift that can cache JSON, Image, Zip or AnyObject with expiry date/TTYL and force refresh.

Nice threadsafe expirable cache management that can cache any object. Supports fetching from server, single object expire date, UIImageView loading etc.

Sadman Samee 122 Dec 28, 2022
Convert your own struct/enum to AnyObject easily.

AnyObjectConvertible Convert your own struct/enum to AnyObject easily. Sumally We can cast everything as AnyObject at Swift3.0 ?? So, we would not nee

tarunon 62 Feb 2, 2022
NoticeObserveKit is type-safe NotificationCenter wrapper.

NoticeObserveKit NoticeObserveKit is type-safe NotificationCenter wrapper. // .keyboardWillShow is a static property. Notice.Center.default.observe(na

Taiki Suzuki 147 Nov 24, 2022