Last active
September 7, 2018 13:39
-
-
Save freak4pc/e6104b29f84f7f76a07c834233906bfa to your computer and use it in GitHub Desktop.
Simple (Naive) Rx Cart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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