Skip to content

Instantly share code, notes, and snippets.

@Gurpartap
Last active February 19, 2018 12:56
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 Gurpartap/5542e618de9097b71fea46cd8c4bd6d3 to your computer and use it in GitHub Desktop.
Save Gurpartap/5542e618de9097b71fea46cd8c4bd6d3 to your computer and use it in GitHub Desktop.
rx_autoUpdater for ObservableArray-RxSwift
import UIKit
import RxSwift
import ObservableArray_RxSwift
extension UITableView {
public func rx_autoUpdater(source: Observable<ArrayChangeEvent>) -> Disposable {
return source
.scan((0, nil)) { (a: (Int, ArrayChangeEvent?), ev) in
(a.0 + ev.insertedIndices.count - ev.deletedIndices.count, ev)
}
.observeOn(MainScheduler.instance)
.subscribe(onNext: { sourceCount, event in
guard let event = event else { return }
let tableCount = self.numberOfRows(inSection: 0)
guard tableCount + event.insertedIndices.count - event.deletedIndices.count == sourceCount else {
self.reloadData()
return
}
func toIndexSet(array: [Int]) -> [IndexPath] {
return array.map { IndexPath(row: $0, section: 0) }
}
self.beginUpdates()
self.insertRows(at: toIndexSet(array: event.insertedIndices), with: .automatic)
self.deleteRows(at: toIndexSet(array: event.deletedIndices), with: .automatic)
self.reloadRows(at: toIndexSet(array: event.updatedIndices), with: .automatic)
self.endUpdates()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment