Skip to content

Instantly share code, notes, and snippets.

@joshdholtz
Last active October 5, 2016 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshdholtz/11018852878a619380a890f47af2a260 to your computer and use it in GitHub Desktop.
Save joshdholtz/11018852878a619380a890f47af2a260 to your computer and use it in GitHub Desktop.
RxSwift - Create historical observable to see how the data changed
extension Observable {
func asHistoricalObservable() -> Observable<(previous: Element, next: Element)> {
return makeHistoricalObservable(observable: self)
}
}
extension Variable {
func asHistoricalObservable() -> Observable<(previous: Element, next: Element)> {
return makeHistoricalObservable(observable: self.asObservable())
}
}
fileprivate func makeHistoricalObservable<E>(observable: Observable<E>) -> Observable<(previous: E, next: E)> {
return Observable.zip(observable, observable.skip(1)) { (previous: E, next: E) -> (E, E) in
return (previous: previous, next: next)
}
}
let dataForTable = Variable(["Some data", "Goes here", "And changes"])
dataForTable.asHistoricalObservable().subscribe { [weak self] (event) in
let previous = event.element?.previous ?? []
let next = event.element?.next ?? []
print("Previous count - \(previous.count)")
print("Nex count - \(next.count)")
// Insert and/or delete rows in table view here
}.addDisposableTo(disposeBag)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment