Skip to content

Commit 0a787cb

Browse files
committed
Improve count implementation
1 parent dd66b5d commit 0a787cb

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

RxQueryKit/RxQueryKit.swift

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import CoreData
22
import RxSwift
33
import QueryKit
4+
import Foundation
45

56

67
/// Extension to QuerySet to provide observables
@@ -16,8 +17,29 @@ extension QuerySet {
1617
/// Performs a query for the count of all objects matching the set predicate.
1718
/// Emits an Int containing the amount of objects matching the predicate and updates when the managed object context is changed.
1819
func count() throws -> Observable<Int> {
19-
return context.qk_objectsDidChange().map { [unowned self] notification in
20-
return try self.count()
21-
}.startWith(try self.count())
20+
var count:Int = try self.count()
21+
22+
return AnonymousObservable { observer in
23+
observer.on(.Next(count))
24+
25+
return self.context.qk_objectsDidChange().subscribeNext { notification in
26+
let insertedObjects = notification.insertedObjects.filter {
27+
$0.entity.name == self.entityName
28+
}
29+
let deletedObjects = notification.deletedObjects.filter {
30+
$0.entity.name == self.entityName
31+
}
32+
33+
if let predicate = self.predicate {
34+
count += (insertedObjects as NSArray).filteredArrayUsingPredicate(predicate).count
35+
count += (deletedObjects as NSArray).filteredArrayUsingPredicate(predicate).count
36+
} else {
37+
count -= insertedObjects.count
38+
count -= deletedObjects.count
39+
}
40+
41+
observer.on(.Next(count))
42+
}
43+
}
2244
}
2345
}

0 commit comments

Comments
 (0)