Skip to content

Instantly share code, notes, and snippets.

@freak4pc
Last active September 7, 2018 13:39

Revisions

  1. freak4pc revised this gist Sep 7, 2018. 1 changed file with 15 additions and 2 deletions.
    17 changes: 15 additions & 2 deletions Cart.swift
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    struct Cart {
    public let action = PublishRelay<Action>()
    private let action = PublishRelay<Action>()
    public let items: Observable<[Item]>

    init() {
    @@ -22,6 +22,19 @@ extension Cart {
    }
    }

    extension Cart: ObserverType {
    func on(_ event: Event<Cart.Action>) {
    switch event {
    case .next(let newAction):
    action.accept(newAction)
    default:
    break // ignore
    }
    }

    typealias E = Cart.Action
    }

    /// ### USAGE

    let cart = Cart()
    @@ -46,5 +59,5 @@ Observable<Cart.Action>
    .remove(items[3]),
    .remove(items[1])
    )
    .bind(to: cart.action)
    .bind(to: cart)
    .disposed(by: disposeBag)
  2. freak4pc revised this gist Sep 7, 2018. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion Cart.swift
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,4 @@
    struct Cart {
    // private let _items = BehaviorRelay<[Item]>(value: [])
    public let action = PublishRelay<Action>()
    public let items: Observable<[Item]>

  3. freak4pc created this gist Sep 7, 2018.
    51 changes: 51 additions & 0 deletions Cart.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    struct Cart {
    // private let _items = BehaviorRelay<[Item]>(value: [])
    public let action = PublishRelay<Action>()
    public let items: Observable<[Item]>

    init() {
    items = action
    .scan([Item]()) { items, action in
    switch action {
    case .add(let item):
    return items + [item]
    case .remove(let item):
    return items.filter { $0.id != item.id }
    }
    }
    }
    }

    extension Cart {
    enum Action {
    case add(Item)
    case remove(Item)
    }
    }

    /// ### USAGE

    let cart = Cart()
    let items = [
    "Coffee",
    "Tea",
    "Biscuit",
    "Something"
    ].map(Item.init)

    cart.items
    .debug("cart")
    .subscribe()
    .disposed(by: disposeBag)

    // Some stream of actions coming from outside
    Observable<Cart.Action>
    .of (.add(items[0]),
    .add(items[1]),
    .add(items[3]),
    .add(items[2]),
    .remove(items[3]),
    .remove(items[1])
    )
    .bind(to: cart.action)
    .disposed(by: disposeBag)