Skip to content

Commit

Permalink
Add a method that can replace items of a section.
Browse files Browse the repository at this point in the history
  • Loading branch information
srdanrasic committed Mar 26, 2019
1 parent 24fb161 commit f1f3d23
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,7 @@ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
data.moveItem(from: IndexPath(item: 0, section: 1), to: IndexPath(item: 0, section: 0))
}

DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
data.replaceItems(ofSectionAt: 1, with: [1, 100, 20], performDiff: true)
}
//: [Next](@next)
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import ReactiveKit

let tableView = UITableView()
tableView.frame.size = CGSize(width: 300, height: 600)
tableView.rowHeight = 40

// Note: Open the assistant editor to see the table view
PlaygroundPage.current.liveView = tableView
Expand Down Expand Up @@ -54,4 +55,8 @@ DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
data.moveItem(from: IndexPath(item: 0, section: 1), to: IndexPath(item: 0, section: 0))
}

DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
data.replaceItems(ofSectionAt: 1, with: [1, 100, 20], performDiff: true)
}

//: [Next](@next)
18 changes: 18 additions & 0 deletions Sources/Bond/Observable Collections/TreeChangeset+Array2D.swift
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,21 @@ extension MutableChangesetContainerProtocol where Changeset: TreeChangesetProtoc
removeAll()
}
}

extension MutableChangesetContainerProtocol where Changeset: TreeChangesetProtocol, Changeset.Collection: Array2DProtocol, Changeset.Collection.Item: Equatable {

/// Replace items of a section at the given index with new items. Setting `performDiff: true` will make the framework
/// calculate the diff between the existing and new items and emit an event with the calculated diff.
public func replaceItems(ofSectionAt sectionIndex: Int, with newItems: [Item], performDiff: Bool) {
guard performDiff else {
self[sectionAt: sectionIndex].items = newItems
return
}
let currentItems = self[sectionAt: sectionIndex].items
let diff = OrderedCollectionDiff<Int>(from: currentItems.extendedDiff(newItems, isEqual: ==))
descriptiveUpdate { (collection) -> Diff in
collection[childAt: [sectionIndex]].children = newItems.map { Array2D.Node.item($0) }
return diff.map { [sectionIndex, $0] }
}
}
}

0 comments on commit f1f3d23

Please sign in to comment.