Last active
February 19, 2018 12:56
-
-
Save Gurpartap/5542e618de9097b71fea46cd8c4bd6d3 to your computer and use it in GitHub Desktop.
rx_autoUpdater for ObservableArray-RxSwift
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 characters
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