Last active
September 7, 2018 13:39
Revisions
-
freak4pc revised this gist
Sep 7, 2018 . 1 changed file with 15 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,5 +1,5 @@ struct Cart { 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) .disposed(by: disposeBag) -
freak4pc revised this gist
Sep 7, 2018 . 1 changed file with 0 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -1,5 +1,4 @@ struct Cart { public let action = PublishRelay<Action>() public let items: Observable<[Item]> -
freak4pc created this gist
Sep 7, 2018 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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)