Skip to content

Commit e9e86e2

Browse files
committed
[Count] Reset count when objects are modified
1 parent 4fd520b commit e9e86e2

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
# RxQueryKit
22

3+
## Master
4+
5+
### Bug Fixes
6+
7+
- Fixes a bug where `count()` using a predicate may have not counted objects
8+
that have been modified to come into the predicate.
9+
310
## 0.5.2
411

512
### Bug Fixes

RxQueryKit/RxQueryKit.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,20 @@ extension QuerySet {
4848
observer.on(.Next(count))
4949

5050
return self.context.qk_objectsDidChange().subscribeNext { notification in
51+
let updatedObjects = notification.updatedObjects.filter {
52+
$0.entity.name == self.entityName
53+
}
54+
55+
if !updatedObjects.isEmpty {
56+
do {
57+
count = try self.count()
58+
observer.onNext(count)
59+
} catch {
60+
observer.onError(error)
61+
}
62+
return
63+
}
64+
5165
let insertedObjects = notification.insertedObjects.filter {
5266
$0.entity.name == self.entityName
5367
}

RxQueryKitTests/RxQueryKitTests.swift

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,45 @@ class RxQueryKitTests: XCTestCase {
5353
disposable.dispose()
5454
}
5555

56+
func testCountWithPredicate() {
57+
var counts: [Int] = []
58+
let disposable = try! Person.queryset(context)
59+
.filter { $0.name != "kyle" }
60+
.count()
61+
.subscribeNext {
62+
counts.append($0)
63+
}
64+
65+
// Initial value
66+
XCTAssertEqual(counts, [0])
67+
68+
// Created
69+
let p1 = Person.create(context, name: "kyle1")
70+
Person.create(context, name: "kyle2")
71+
let p3 = Person.create(context, name: "kyle3")
72+
let p4 = Person.create(context, name: "kyle")
73+
try! context.save()
74+
XCTAssertEqual(counts, [0, 3])
75+
76+
// Deleted
77+
context.deleteObject(p1)
78+
context.deleteObject(p3)
79+
try! context.save()
80+
XCTAssertEqual(counts, [0, 3, 1])
81+
82+
// Doesn't update when nothing changes
83+
Comment.create(context, text: "Hello World")
84+
try! context.save()
85+
XCTAssertEqual(counts, [0, 3, 1])
86+
87+
// Modify comes into count
88+
p4.name = "kyle4"
89+
try! context.save()
90+
XCTAssertEqual(counts, [0, 3, 1, 2])
91+
92+
disposable.dispose()
93+
}
94+
5695
func testObjects() {
5796
var objects: [[Person]] = []
5897

0 commit comments

Comments
 (0)