Skip to content

Instantly share code, notes, and snippets.

@freak4pc
Last active September 7, 2018 13:39
Show Gist options
  • Save freak4pc/e6104b29f84f7f76a07c834233906bfa to your computer and use it in GitHub Desktop.
Save freak4pc/e6104b29f84f7f76a07c834233906bfa to your computer and use it in GitHub Desktop.
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