Merge pull request #454 from groue/feature/distinctUntilChanged

ValueObservation.distinctUntilChanged
This commit is contained in:
Gwendal Roué authored and GitHub committed 2018-12-05 12:06:42 +01:00
commit 643bbc7076
14 files changed
+262 -115

No files matched your search

+3 -6
View File
@@ -52,23 +52,20 @@ GRDB adheres to [Semantic Versioning](https://semver.org/).
- [#442](https://github.com/groue/GRDB.swift/pull/442): Reindex
- [#443](https://github.com/groue/GRDB.swift/pull/443): In place record update
- [#446](https://github.com/groue/GRDB.swift/pull/446): ValueObservation: delayed reducer creation
- [#444](https://github.com/groue/GRDB.swift/pull/444): Combine Value Observations
- [#451](https://github.com/groue/GRDB.swift/pull/451): ValueObservation.compactMap
- [#452](https://github.com/groue/GRDB.swift/pull/452): ValueObservation.mapReducer
- [#454](https://github.com/groue/GRDB.swift/pull/454): ValueObservation.distinctUntilChanged
- [#445](https://github.com/groue/GRDB.swift/pull/445): Quality of service and target dispatch queue
- ValueObservation methods which used to accept a variadic list of observed regions now also accept an array.
- ValueReducer, the protocol that fuels ValueObservation, is flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). It will remain so until more experience has been acquired.
### Breaking Change
- [#446](https://github.com/groue/GRDB.swift/pull/446): ValueObservation: delayed reducer creation
### Documentation Diff
- [Record Comparison](README.md#record-comparison): this chapter has been updated for the new `updateChanges(_:with:)` method.
- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine(...)` and `ValueObservation.compactMap(...)` methods.
- [ValueObservation](README.md#valueobservation): this chapter has been updated for the new `ValueObservation.combine`, `ValueObservation.compactMap`, and `Value.distinctUntilChanged` methods.
### API diff
+8
View File
@@ -214,6 +214,9 @@
564CE52021B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; };
564CE52121B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; };
564CE52221B3129A00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */; };
564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564E73DF203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73DE203D50B9000C443C /* JoinSupportTests.swift */; };
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
@@ -978,6 +981,7 @@
564CE4E521B2E06700652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = "<group>"; };
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = "<group>"; };
564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = "<group>"; };
564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
@@ -1405,6 +1409,7 @@
564CE4D521B2DEB500652B19 /* ValueObservation+CompactMap.swift */,
5613ED5321A95DD000DC7A68 /* ValueObservation+Count.swift */,
5613ED4F21A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */,
564CE59621B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift */,
5613ED4B21A95C4300DC7A68 /* ValueObservation+FetchableRecord.swift */,
5613ED3421A95A5C00DC7A68 /* ValueObservation+Map.swift */,
564CE51F21B3129900652B19 /* ValueObservation+MapReducer.swift */,
@@ -2484,6 +2489,7 @@
56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
5613ED5221A95C6D00DC7A68 /* ValueObservation+DatabaseValueConvertible.swift in Sources */,
5653EB0B20944C7C00F46237 /* Association.swift in Sources */,
564CE59F21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */,
56D121601ED34978001347D2 /* Fixits-0.109.0.swift in Sources */,
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
@@ -2728,6 +2734,7 @@
56CEB5641EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
56873BEF1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */,
564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */,
564CE59E21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
56B964A01DA51B4C0002DA19 /* FTS5.swift in Sources */,
5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */,
);
@@ -3121,6 +3128,7 @@
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
56CEB5611EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
564CE59D21B7A8B500652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
5605F1591C672E4000235C62 /* CGFloat.swift in Sources */,
@@ -26,8 +26,9 @@ extension ValueObservation where Reducer == Void {
/// - parameter request: the observed request.
/// - returns: a ValueObservation.
public static func trackingCount<Request: FetchRequest>(_ request: Request)
-> ValueObservation<DistinctValueReducer<Int>>
-> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Int>>>
{
return ValueObservation.tracking(request, fetchDistinct: request.fetchCount)
// TODO: Remove distinctUntilChanged in GRDB 4
return ValueObservation.tracking(request, fetch: request.fetchCount).distinctUntilChanged()
}
}
@@ -124,6 +124,7 @@ public struct DatabaseValuesReducer<Request: FetchRequest>: ValueReducer
public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder]? {
if let previousDbValues = previousDbValues, previousDbValues == dbValues {
// Don't notify consecutive identical dbValue arrays
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
return nil
}
self.previousDbValues = dbValues
@@ -157,6 +158,7 @@ public struct DatabaseValueReducer<Request: FetchRequest>: ValueReducer
public mutating func value(_ dbValue: DatabaseValue?) -> Request.RowDecoder?? {
if let previousDbValue = previousDbValue, previousDbValue == dbValue {
// Don't notify consecutive identical dbValue
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
return nil
}
self.previousDbValue = dbValue
@@ -167,6 +169,7 @@ public struct DatabaseValueReducer<Request: FetchRequest>: ValueReducer
return .some(value)
} else if previousValueWasNil {
// Don't notify consecutive nil values
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
return nil
} else {
previousValueWasNil = true
@@ -200,6 +203,7 @@ public struct OptionalDatabaseValuesReducer<Request: FetchRequest>: ValueReducer
public mutating func value(_ dbValues: [DatabaseValue]) -> [Request.RowDecoder._Wrapped?]? {
if let previousDbValues = previousDbValues, previousDbValues == dbValues {
// Don't notify consecutive identical dbValue arrays
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
return nil
}
self.previousDbValues = dbValues
@@ -0,0 +1,47 @@
extension ValueObservation where Reducer: ValueReducer, Reducer.Value: Equatable {
/// Returns a ValueObservation which filters out consecutive equal values.
public func distinctUntilChanged()
-> ValueObservation<DistinctUntilChangedValueReducer<Reducer>>
{
return mapReducer { $1.distinctUntilChanged() }
}
}
extension ValueReducer where Value: Equatable {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// Returns a ValueReducer which filters out consecutive equal values.
public func distinctUntilChanged() -> DistinctUntilChangedValueReducer<Self> {
return DistinctUntilChangedValueReducer(self)
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// See ValueReducer.distinctUntilChanged()
///
/// :nodoc:
public struct DistinctUntilChangedValueReducer<Base: ValueReducer>: ValueReducer where Base.Value: Equatable {
private var base: Base
private var previousValue: Base.Value?
init(_ base: Base) {
self.base = base
}
public func fetch(_ db: Database) throws -> Base.Fetched {
return try base.fetch(db)
}
public mutating func value(_ fetched: Base.Fetched) -> Base.Value? {
guard let value = base.value(fetched) else {
return nil
}
if let previousValue = previousValue, previousValue == value {
// Don't notify consecutive identical values
return nil
}
self.previousValue = value
return value
}
}
@@ -91,6 +91,7 @@ public struct FetchableRecordsReducer<Request: FetchRequest>: ValueReducer
public mutating func value(_ rows: [Row]) -> [Request.RowDecoder]? {
if let previousRows = previousRows, previousRows == rows {
// Don't notify consecutive identical row arrays
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
return nil
}
self.previousRows = rows
@@ -121,6 +122,7 @@ public struct FetchableRecordReducer<Request: FetchRequest>: ValueReducer
public mutating func value(_ row: Row?) -> Request.RowDecoder?? {
if let previousRow = previousRow, previousRow == row {
// Don't notify consecutive identical rows
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
return nil
}
self.previousRow = row
@@ -120,6 +120,7 @@ public struct RowReducer<Request: FetchRequest>: ValueReducer
public mutating func value(_ row: Row?) -> Row?? {
if let previousRow = previousRow, previousRow == row {
// Don't notify consecutive identical rows
// TODO: Remove this implicit `distinctUntilChanged` in GRDB 4
return nil
}
self.previousRow = row
+59 -55
View File
@@ -207,7 +207,7 @@ extension ValueObservation {
// MARK: - Creating ValueObservation from ValueReducer
/// Returs a ValueObservation which observes *regions*, and notifies the
/// Returns a ValueObservation which observes *regions*, and notifies the
/// values returned by the *reducer* whenever one of the observed
/// regions is modified by a database transaction.
///
@@ -217,13 +217,54 @@ extension ValueObservation {
/// table is modified:
///
/// var count = 0
/// let observation = ValueObservation.tracking(Player.all(), reducer: ( db in
/// AnyValueReducer(
/// fetch: { _ in },
/// value: { _ -> Int? in
/// count += 1
/// return count })
/// })
/// let reducer = AnyValueReducer(
/// fetch: { _ in },
/// value: { _ -> Int? in
/// count += 1
/// return count })
/// let observation = ValueObservation.tracking(Player.all(), reducer: reducer)
/// let observer = observation.start(in: dbQueue) { count: Int in
/// print("Players have been modified \(count) times.")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter regions: A list of observed regions.
/// - parameter reducer: A reducer that turns database changes in the
/// modified regions into fresh values. Currently only reducers that adopt
/// the ValueReducer protocol are supported.
@available(*, deprecated, message: "Provide the reducer in a (Database) -> Reducer closure")
public static func tracking(
_ regions: DatabaseRegionConvertible...,
reducer: Reducer)
-> ValueObservation
{
return ValueObservation.tracking(regions, reducer: { _ in reducer })
}
/// Returns a ValueObservation which observes *regions*, and notifies the
/// values returned by the *reducer* whenever one of the observed
/// regions is modified by a database transaction.
///
/// This method is the most fundamental way to create a ValueObservation.
///
/// For example, this observation counts the number of a times the player
/// table is modified:
///
/// var count = 0
/// let reducer = AnyValueReducer(
/// fetch: { _ in /* don't fetch anything */ },
/// value: { _ -> Int? in
/// defer { count += 1 }
/// return count })
/// let observation = ValueObservation.tracking(Player.all(), reducer: { db in reducer })
/// let observer = observation.start(in: dbQueue) { count: Int in
/// print("Players have been modified \(count) times.")
/// }
@@ -249,7 +290,7 @@ extension ValueObservation {
return ValueObservation.tracking(regions, reducer: reducer)
}
/// Returs a ValueObservation which observes *regions*, and notifies the
/// Returns a ValueObservation which observes *regions*, and notifies the
/// values returned by the *reducer* whenever one of the observed
/// regions is modified by a database transaction.
///
@@ -259,13 +300,12 @@ extension ValueObservation {
/// table is modified:
///
/// var count = 0
/// let observation = ValueObservation.tracking([Player.all()], reducer: ( db in
/// AnyValueReducer(
/// fetch: { _ in },
/// value: { _ -> Int? in
/// count += 1
/// return count })
/// })
/// let reducer = AnyValueReducer(
/// fetch: { _ in /* don't fetch anything */ },
/// value: { _ -> Int? in
/// defer { count += 1 }
/// return count })
/// let observation = ValueObservation.tracking([Player.all()], reducer: { db in reducer })
/// let observer = observation.start(in: dbQueue) { count: Int in
/// print("Players have been modified \(count) times.")
/// }
@@ -392,49 +432,13 @@ extension ValueObservation where Reducer == Void {
///
/// - parameter regions: A list of observed regions.
/// - parameter fetch: A closure that fetches a value.
@available(*, deprecated, message: "Use distinctUntilChanged() instead")
public static func tracking<Value>(
_ regions: DatabaseRegionConvertible...,
fetchDistinct fetch: @escaping (Database) throws -> Value)
-> ValueObservation<DistinctValueReducer<Value>>
-> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>>
where Value: Equatable
{
return ValueObservation.tracking(regions, fetchDistinct: fetch)
}
/// Creates a ValueObservation which observes *regions*, and notifies the
/// values returned by the *fetch* closure whenever one of the observed
/// regions is modified by a database transaction. Consecutive equal values
/// are filtered out.
///
/// For example:
///
/// let observation = ValueObservation.tracking(
/// [Player.all()],
/// fetchDistinct: { db in return try Player.fetchAll(db) })
///
/// let observer = try observation.start(in: dbQueue) { players: [Player] in
/// print("Players have changed")
/// }
///
/// The returned observation has the default configuration:
///
/// - When started with the `start(in:onError:onChange:)` method, a fresh
/// value is immediately notified on the main queue.
/// - Upon subsequent database changes, fresh values are notified on the
/// main queue.
/// - The observation lasts until the observer returned by
/// `start` is deallocated.
///
/// - parameter regions: A list of observed regions.
/// - parameter fetch: A closure that fetches a value.
public static func tracking<Value>(
_ regions: [DatabaseRegionConvertible],
fetchDistinct fetch: @escaping (Database) throws -> Value)
-> ValueObservation<DistinctValueReducer<Value>>
where Value: Equatable
{
return ValueObservation<DistinctValueReducer<Value>>(
tracking: DatabaseRegion.union(regions),
reducer: { _ in DistinctValueReducer(fetch) })
return ValueObservation.tracking(regions, fetch: fetch).distinctUntilChanged()
}
}
-26
View File
@@ -90,29 +90,3 @@ public struct RawValueReducer<Value>: ValueReducer {
}
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// A reducer which filters out consecutive values that are equal.
///
/// :nodoc:
public struct DistinctValueReducer<Value: Equatable>: ValueReducer {
private let _fetch: (Database) throws -> Value
private var previousValue: Value??
public init(_ fetch: @escaping (Database) throws -> Value) {
self._fetch = fetch
}
public func fetch(_ db: Database) throws -> Value {
return try _fetch(db)
}
public mutating func value(_ value: Value) -> Value? {
if let previousValue = previousValue, previousValue == value {
// Don't notify consecutive identical values
return nil
}
self.previousValue = value
return value
}
}
+6
View File
@@ -274,6 +274,8 @@
564CE4F421B2E08A00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */; };
564CE52621B312B500652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; };
564CE52721B312B700652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */; };
564CE5A621B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564CE5A721B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73EB203DA29B000C443C /* JoinSupportTests.swift */; };
@@ -1090,6 +1092,7 @@
564CE4EB21B2E08200652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = "<group>"; };
564CE4F021B2E08A00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = "<group>"; };
564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = "<group>"; };
564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
@@ -1487,6 +1490,7 @@
564CE4DC21B2DEF700652B19 /* ValueObservation+CompactMap.swift */,
5613ED7A21A95E8400DC7A68 /* ValueObservation+Count.swift */,
5613ED7821A95E8400DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */,
564CE5A421B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift */,
5613ED7721A95E8400DC7A68 /* ValueObservation+FetchableRecord.swift */,
5613ED7521A95E8400DC7A68 /* ValueObservation+Map.swift */,
564CE51A21B3128400652B19 /* ValueObservation+MapReducer.swift */,
@@ -2331,6 +2335,7 @@
56CEB5621EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
564CE5A621B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
566B91141FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
560FC51F1CB003810014AA8E /* CGFloat.swift in Sources */,
5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
@@ -2815,6 +2820,7 @@
56CEB5651EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
564CE5A721B7A9D600652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
566B91171FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
56AFC9F31CB1A8BB00F48B96 /* Database.swift in Sources */,
5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
+6
View File
@@ -105,6 +105,8 @@
564CE4E421B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; };
564CE52421B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; };
564CE52521B312AD00652B19 /* ValueObservation+MapReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */; };
564CE5A221B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564CE5A321B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */; };
564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; };
564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; };
564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; };
@@ -727,6 +729,7 @@
564CE4DF21B2E04500652B19 /* ValueObservationCompactMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationCompactMapTests.swift; sourceTree = "<group>"; };
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+MapReducer.swift"; sourceTree = "<group>"; };
564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "ValueObservation+DistinctUntilChanged.swift"; sourceTree = "<group>"; };
564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = "<group>"; };
564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = "<group>"; };
564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = "<group>"; };
@@ -1090,6 +1093,7 @@
564CE4D921B2DEEB00652B19 /* ValueObservation+CompactMap.swift */,
5613ED6021A95E6100DC7A68 /* ValueObservation+Count.swift */,
5613ED5E21A95E6100DC7A68 /* ValueObservation+DatabaseValueConvertible.swift */,
564CE5A021B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift */,
5613ED5D21A95E6100DC7A68 /* ValueObservation+FetchableRecord.swift */,
5613ED5B21A95E6100DC7A68 /* ValueObservation+Map.swift */,
564CE52321B312AC00652B19 /* ValueObservation+MapReducer.swift */,
@@ -1970,6 +1974,7 @@
56CEB5661EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
564CE5A321B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
566B91181FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
F3BA80181CFB2876003DC1BA /* SerializedDatabase.swift in Sources */,
5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
@@ -2275,6 +2280,7 @@
56CEB5631EAA359A00BFAF62 /* SQLSelectable.swift in Sources */,
56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
564CE5A221B7A9C700652B19 /* ValueObservation+DistinctUntilChanged.swift in Sources */,
566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */,
5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
+42 -17
View File
@@ -6267,6 +6267,7 @@ Changes are only notified after they have been committed in the database. No ins
- [ValueObservation Transformations](#valueobservation-transformations)
- [ValueObservation.map](#valueobservationmap)
- [ValueObservation.compactMap](#valueobservationcompactmap)
- [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged)
- [ValueObservation.combine(...)](#valueobservationcombine)
- [ValueObservation Error Handling](#valueobservation-error-handling)
- [ValueObservation Options](#valueobservation-options)
@@ -6377,6 +6378,8 @@ Those observations match the `fetchCount`, `fetchOne`, and `fetchAll` request me
}
```
> :point_up: **Note**: the observations returned by the [ValueObservation.trackingCount, trackingOne, and trackingAll](#valueobservationtrackingcount-trackingone-trackingall) methods perform a filtering of consecutive identical values, based on raw database values.
### ValueObservation.tracking(_:fetch:)
@@ -6436,18 +6439,16 @@ let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in
It may happen that a database change does not modify the observed values. The Hall of Fame, for example, is not affected by changes that happen to the worst players.
When such a database change happens, `ValueObservation.tracking(_:fetch:)` notifies identical consecutive values.
When such a database change happens, `ValueObservation.tracking(_:fetch:)` is triggered, just in case the best players would be modified, and ends up notifying identical consecutive values.
You can filter out those duplicates with the `ValueObservation.tracking(_:fetchDistinct:)` method. It requires the observed value to adopt the Equatable protocol:
You can filter out those duplicates with the [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged) method. It requires the observed value to adopt the Equatable protocol:
```swift
extension HallOfFame: Equatable { ... }
let observation = ValueObservation.tracking(
Player.all(),
fetchDistinct: { db -> HallOfFame in
return HallOfFame.fetch(db)
})
let observation = ValueObservation
.tracking(Player.all(), fetch: HallOfFame.fetch)
.distinctUntilChanged()
let observer = observation.start(in: dbQueue) { hallOfFame: HallOfFame in
print("""
@@ -6524,6 +6525,7 @@ let observer = ValueObservation
- [ValueObservation.map](#valueobservationmap)
- [ValueObservation.compactMap](#valueobservationcompactmap)
- [ValueObservation.distinctUntilChanged](#valueobservationdistinctuntilchanged)
- [ValueObservation.combine(...)](#valueobservationcombine)
@@ -6567,6 +6569,30 @@ let observer = observation.start(in: dbQueue) { player: Player in
The transformation closure does not run on the main queue, and is suitable for heavy computations.
#### ValueObservation.distinctUntilChanged
The `distinctUntilChanged` method filters out the consecutive equal values notified by a ValueObservation. The observed values must adopt the standard Equatable protocol.
For example:
```swift
let observation = ValueObservation
.trackingOne(Player.filter(key: 42))
.map { player in player != nil } // existence test
.distinctUntilChanged()
let observer = observation.start(in: dbQueue) { exists: Bool in
if exists {
print("Player 42 exists.")
} else {
print("Player 42 does not exist.")
}
}
```
> :point_up: **Note**: the observations returned by the [ValueObservation.trackingCount, trackingOne, and trackingAll](#valueobservationtrackingcount-trackingone-trackingall) methods already perform a similar filtering, based on raw database values.
#### ValueObservation.combine(...)
Sometimes you need to observe several requests at the same time. For example, you need to observe changes in both a team and its players.
@@ -6759,22 +6785,21 @@ The sample code below counts the number of times the player table is modified:
```swift
var count = 0
let observation = ValueObservation.tracking(Player.all(), reducer: { _ in
AnyValueReducer(
fetch: { _ in /* don't fetch anything */ },
value: { _ -> Int? in
defer { count += 1 }
return count })
})
let reducer = AnyValueReducer(
fetch: { _ in /* don't fetch anything */ },
value: { _ -> Int? in
defer { count += 1 }
return count })
let observation = ValueObservation.tracking(Player.all(), reducer: { _ in reducer })
let observer = observation.start(in: dbQueue) { count: Int in
print("\(count) transaction(s) have modified the players.")
print("Number of transactions that have modified players: \(count)")
}
// Prints "0 transaction(s) have modified the players."
// Prints "Number of transactions that have modified players: 0"
try dbQueue.write { db in
try Player(...).insert(db)
}
// Prints "1 transaction(s) have modified the players."
// Prints "Number of transactions that have modified players: 1"
```
@@ -22,7 +22,6 @@ class ValueObservationFetchTests: GRDBTestCase {
_ = ValueObservation.tracking(DatabaseRegion(), DatabaseRegion(), fetchDistinct: { _ in 0 })
// array
_ = ValueObservation.tracking([DatabaseRegion()], fetch: { _ in })
_ = ValueObservation.tracking([DatabaseRegion()], fetchDistinct: { _ in 0 })
}
func testFetch() throws {
@@ -57,7 +56,8 @@ class ValueObservationFetchTests: GRDBTestCase {
try test(makeDatabasePool())
}
func testFetchWithUniquing() throws {
// Test for a deprecated API
func testFetchDistinct() throws {
func test(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
@@ -88,4 +88,36 @@ class ValueObservationFetchTests: GRDBTestCase {
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
func testDistinctUntilChanged() throws {
func test(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
var counts: [Int] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 3
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, fetch: {
try Int.fetchOne($0, "SELECT COUNT(*) FROM t")!
}).distinctUntilChanged()
observation.extent = .databaseLifetime
_ = try observation.start(in: dbWriter) { count in
counts.append(count)
notificationExpectation.fulfill()
}
try dbWriter.writeWithoutTransaction { db in
try db.execute("INSERT INTO t DEFAULT VALUES")
try db.execute("UPDATE t SET id = id")
try db.execute("INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(counts, [0, 1, 2])
}
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
}
@@ -205,6 +205,47 @@ class ValueObservationReducerTests: GRDBTestCase {
try test(makeDatabasePool())
}
func testDeprecatedReadMeReducer() throws {
func test(_ dbWriter: DatabaseWriter) throws {
// Test for the reducer documented in the main README
// We need something to change
try dbWriter.write { try $0.execute("CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") }
// Track reducer process
var counts: [Int] = []
let notificationExpectation = expectation(description: "notification")
notificationExpectation.assertForOverFulfill = true
notificationExpectation.expectedFulfillmentCount = 2
// Create an observation
var count = 0
let reducer = AnyValueReducer(
fetch: { _ in /* don't fetch anything */ },
value: { _ -> Int? in
defer { count += 1 }
return count })
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: reducer)
observation.extent = .databaseLifetime
// Start observation
_ = try observation.start(in: dbWriter) { count in
counts.append(count)
notificationExpectation.fulfill()
}
try dbWriter.write { db in
try db.execute("INSERT INTO t DEFAULT VALUES")
}
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(counts, [0, 1])
}
try test(makeDatabaseQueue())
try test(makeDatabasePool())
}
func testReadMeReducer() throws {
func test(_ dbWriter: DatabaseWriter) throws {
// Test for the reducer documented in the main README
@@ -220,13 +261,12 @@ class ValueObservationReducerTests: GRDBTestCase {
// Create an observation
var count = 0
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in
AnyValueReducer(
fetch: { _ in /* don't fetch anything */ },
value: { _ -> Int? in
defer { count += 1 }
return count })
})
let reducer = AnyValueReducer(
fetch: { _ in /* don't fetch anything */ },
value: { _ -> Int? in
defer { count += 1 }
return count })
var observation = ValueObservation.tracking(DatabaseRegion.fullDatabase, reducer: { _ in reducer})
observation.extent = .databaseLifetime
// Start observation