Skip to content

Instantly share code, notes, and snippets.

@freak4pc freak4pc/Cart.swift
Last active Sep 7, 2018

Embed
What would you like to do?
Simple (Naive) Rx Cart
struct Cart {
private 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)
}
}
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()
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)
.disposed(by: disposeBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.