Rewrite ValueObservation documentation

This commit is contained in:
Gwendal Roué committed 2020-03-24 14:09:45 +01:00
1 parent b3fb61858a
commit cf1360701c
1 file changed
-449
-449
View File
@@ -5870,455 +5870,6 @@ When needed, you can help GRDB optimize observations and reduce database content
The `map` operator helps reducing database contention because it performs its job without blocking concurrent database reads.
---
- **[ValueObservation Usage](#valueobservation-usage)**
- [ValueObservation.tracking(value:)](#valueobservationtrackingvalue)
- [ValueObservation.tracking(_:fetch:)](#valueobservationtracking_fetch)
- [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst)
- [ValueObservation Transformations](#valueobservation-transformations): [map](#valueobservationmap), [removeDuplicates](#valueobservationremoveduplicates), ...
- [ValueObservation Error Handling](#valueobservation-error-handling)
- [ValueObservation Options](#valueobservation-options)
### ValueObservation Usage
Here is a typical UIViewController which observes the database in order to keep its view up-to-date:
```swift
class PlayerViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
private var observer: TransactionObserver?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Define a ValueObservation which tracks a player
let observation = ValueObservation.tracking { db in
try Player.fetchOne(db, key: 42)
}
// Start observing the database
observer = observation.start(
in: dbQueue,
onError: { error in
print("player could not be fetched")
},
onChange: { [weak self] (player: Player?) in
// Player has been refreshed: update view
guard let self = self else { return }
self.nameLabel.text = player?.name
})
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Stop observing the database
observer = nil
}
}
```
By default, all values and errors are notified on the main queue. Views can be updated right from the `onChange` callback.
An initial fetch is performed as soon as the observation starts: the view is set up and ready when the `viewWillAppear` method returns.
The observer returned by the `start` method is stored in a property of the view controller. This allows the view controller to control the duration of the observation. When the observer is deallocated, the observation stops. Meanwhile, all transactions that modify the observed player are notified, and the `nameLabel` is kept up-to-date.
> :bulb: **Tip**: see the [Demo Application] for a sample app that uses ValueObservation.
>
> :bulb: **Tip**: When fetching values is slow, and should never ever block the main queue, opt in for async notifications:
>
> ```swift
> override func viewWillAppear(_ animated: Bool) {
> super.viewWillAppear(animated)
>
> // Define a ValueObservation which tracks a player
> let observation = ValueObservation.tracking { db in
> try Player.fetchOne(db, key: 42)
> }
>
> // Observation is asynchronous
> observation.scheduling = .async(onQueue: .main)
>
> // Start observing the database
> observer = observation.start(
> in: dbQueue,
> onError: { error in
> print("player could not be fetched")
> },
> onChange: { [weak self] (player: Player?) in
> // Player has been refreshed: update view
> guard let self = self else { return }
> self.activityIndicator.stopAnimating()
> self.nameLabel.text = player?.name
> })
>
> // Wait for player
> activityIndicator.startAnimating()
> nameLabel.text = nil
> }
> ```
>
> See [ValueObservation.scheduling](#valueobservationscheduling) for more information.
### ValueObservation.tracking(value:)
In order to observe database values, you will generally define a **ValueObservation** which tracks the value you are interested in, and then start the observation.
For example:
```swift
// Track changes in a single player
let observation = ValueObservation.tracking { db in
try Player.fetchOne(db, key: 42)
}
observer = observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { (player: Player?) in
print("Fresh player: \(player)")
})
```
**You can observe several requests and several tables if you need**: all writes that have an impact on the fetched values will trigger the observation, and call the `onChange` function.
**The observation may notify identical consecutive values.** This is because it will fetch a fresh value whenever a change *could* happen. For example, the observation for the maximum player score will notify a fresh value every time a score is changed, inserted, or deleted, even if the maximum score is unchanged:
```swift
// Track changes in the maximum player score
// This observation may notify duplicate values
let observation = ValueObservation.tracking { db in
try Player.select(max(Column("score")), as: Int.self).fetchOne(db)
}
```
You can filter out those duplicates with the [removeDuplicates](#valueobservationremoveduplicates) method. It requires the observed value to adopt the Equatable protocol:
```swift
let observation = ValueObservation
.tracking { db in
try Player.select(max(Column("score")), as: Int.self).fetchOne(db)
}
.removeDuplicates()
```
We will see below other ways to define observations. They all add a little convenience, or optimization.
### ValueObservation.tracking(_:fetch:)
The `ValueObservation.tracking(_:fetch:)` method is an **optimized** version of the [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue) method seen above.
The returned observation outputs exactly the same results, but it can perform better when you use a [database pool](#database-pools), and the fetch is slow. It reduces write contention by fetching fresh values without blocking write accesses. When you use a [database queue](#database-queues), no optimization is applied.
It accepts two arguments:
1. A list of observed requests.
2. A closure that fetches a fresh value whenever one of the observed requests are modified.
Changes that happen outside of the observed requests are ignored, so make sure you fully cover the database region you want to observe. This is the price you pay for the optimization.
Let's give a practical example, and observe the "Hall of Fame":
```swift
struct HallOfFame {
var totalPlayerCount: Int
var bestPlayers: [Player]
}
extension HallOfFame {
/// Fetch the HallOfFame
static fetch(_ db: Database) throws -> HallOfFame {
let totalPlayerCount = try Player.fetchCount(db)
let bestPlayers = try Player
.order(Column("score").desc)
.limit(10)
.fetchAll(db)
return HallOfFame(
totalPlayerCount: totalPlayerCount,
bestPlayers: bestPlayers)
}
}
```
In order to track changes in the Hall of Fame in an optimized way, we see that any change to the `player` table can impact the Hall of Fame. We thus track the request for all players, `Player.all()`, and fetch a new Hall of Fame whenever players change:
```swift
let observation = ValueObservation.tracking(Player.all(), fetch: { db in
try HallOfFame.fetch(db)
})
```
> :point_up: **Note**: the initial parameter of `ValueObservation.tracking(_:fetch:)` can be fed with requests, and generally speaking, values that adopt the [DatabaseRegionConvertible] protocol.
### observationForCount, observationForAll, observationForFirst
Given a [request](#requests), even a [custom request](#custom-requests), you can observe its number of results, all results, or the first one:
```swift
request.observationForCount()
request.observationForAll()
request.observationForFirst()
```
Those observations are equivalent to the following ones, defined with [`ValueObservation.tracking(value:)`](#valueobservationtrackingvalue):
```swift
ValueObservation.tracking { db in try request.fetchCount(db) }
ValueObservation.tracking { db in try request.fetchAll(db) }
ValueObservation.tracking { db in try request.fetchOne(db) }
```
Yet they are **optimized**:
- They perform a filtering of consecutive identical values, based on raw database values, so that you are not notified of database changes that do not impact the result of the request.
- They can perform better when you use a [database pool](#database-pools), and the fetch is slow.
### ValueObservation Transformations
- [ValueObservation.map](#valueobservationmap)
- [ValueObservation.removeDuplicates](#valueobservationremoveduplicates)
- [ValueObservation.combine(...)](#valueobservationcombine)
#### ValueObservation.map
The `map` method lets you transform the values notified by a ValueObservation.
For example:
```swift
// Observe a player's profile image
let observation = ValueObservation
.tracking { db in try Player.fetchOne(db, key: 42) }
.map { player in player?.image }
let observer = observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { (image: UIImage?) in
print("Player picture has changed")
})
```
The transformation closure does not run on the main queue, and does not block any database access.
#### ValueObservation.removeDuplicates
The `removeDuplicates` 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
.tracking { db in try Player.fetchOne(db, key: 42) }
.removeDuplicates()
let observer = observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { (player: Player) in
print("Player: \(player)")
})
```
> :point_up: **Note**: the observations returned by the [observationForCount, observationForAll, observationForFirst](#observationforcount-observationforall-observationforfirst) methods already perform a similar filtering, based on raw database values.
#### ValueObservation.combine(...)
The `ValueObservation.combine(...)` method builds a single observation from several:
```swift
// Two base observations
let playerCountObservation = ValueObservation.tracking { db in
try Player.fetchCount(db)
}
let bestPlayersObservation = ValueObservation.tracking { db in
try Player
.limit(10)
.order(Column("score").desc)
.fetchAll(db)
}
// The combined observation
let observation = ValueObservation.combine(
playerCountObservation,
bestPlayersObservation)
// Start tracking the hall of fame
let observer = observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { (totalPlayerCount, bestPlayers) in
print("""
Best players out of \(totalPlayerCount):
\(bestPlayers)
""")
})
```
`combine` also exists as an instance method:
```swift
struct HallOfFame {
var totalPlayerCount: Int
var bestPlayers: [Player]
}
let observation = playerCountObservation.combine(bestPlayersObservation) {
HallOfFame(totalPlayerCount: $0, bestPlayers: $1)
}
```
You can combine up to eight observations together. They can feed from as many database tables as needed.
Combining observations provides the guarantee that notified values are [**consistent**](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
> :point_up: **Note**: readers who are familiar with Reactive Programming will recognize the [CombineLatest](http://reactivex.io/documentation/operators/combinelatest.html) operator in the ValueObservation `combine` method. The reactive operator does not care about data consistency, though: if you use a Reactive layer such as [GRDBCombine] or [RxGRDB], make sure you compose observations with `ValueObservation.combine`, not with the CombineLatest operator.
### ValueObservation Error Handling
When you start an observation, the `onError` callback is called whenever fresh values could not be fetched. It is scheduled just like values (see [ValueObservation.scheduling](#valueobservationscheduling)):
```swift
let observer = observation.start(
in: dbQueue,
onError: { error in
print("fresh value could not be fetched")
},
onChange: { value in
print("fresh value: \(value)")
})
```
An error does not stop the observation. After an error has been received, subsequent transactions may succeed in notifying fresh values. You may witness such temporary errors when the database becomes temporarily unreachable, for example due to [data protection](#data-protection).
Depending on the way your application wants to deal with such errors, you may want to tighten your control on the scheduling of database accesses with [DatabaseRegionObservation]. See also the reactive companion libraries [GRDBCombine] and [RxGRDB], which stop observation whenever a ValueObservation error happens.
### ValueObservation Options
Some behaviors of value observations can be configured:
- [ValueObservation.scheduling](#valueobservationscheduling): Control the dispatching of notified values.
- [ValueObservation.requiresWriteAccess](#valueobservationrequireswriteaccess): Allow observations to write in the database.
#### ValueObservation.scheduling
The `scheduling` property lets you control how fresh values are notified:
- `.mainQueue` (the default): all values are notified on the main queue.
If the observation starts on the main queue, the initial value is notified right upon subscription, synchronously:
```swift
// On main queue
let observer = observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { value in
// On main queue
print("fresh value: \(value)")
})
// <- Here "fresh value" is already printed.
```
If the observation does not start on the main queue, the initial value is also notified on the main queue, but asynchronously:
```swift
// Not on the main queue
let observer = observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { value in
// On main queue
print("fresh value: \(value)")
})
```
After the initial value has been notified, all subsequent values are notified asynchronously:
```swift
try dbQueue.write { db in ... }
// <- Eventually prints "fresh value" on the main queue
```
- `.async(onQueue:)`: all values, including the initial value, are asynchronously notified on the specified queue.
For example:
```swift
// On main queue
var observation = ...
observation.scheduling = .async(onQueue: .main)
let observer = observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { value in
// On main queue
print("fresh value: \(value)")
})
// <- Eventually prints "fresh value"
```
- `unsafe`: values are not all notified on the same dispatch queue.
The initial value is notified right upon subscription, synchronously, on the dispatch queue which starts the observation.
```swift
// On any queue
var observation = ...
observation.scheduling = .unsafe
let observer = observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { value in
print("fresh value: \(value)")
})
// <- Here "fresh value" is already printed.
```
After the initial value has been notified, all subsequent values are notified on unspecified queues.
> :point_up: **Note**: this unsafe mode is intended for third-party libraries that provide their own scheduling engine.
#### ValueObservation.requiresWriteAccess
The `requiresWriteAccess` property is false by default. When true, a ValueObservation has a write access to the database, and its fetches are automatically wrapped in a [savepoint](#transactions-and-savepoints):
```swift
var observation = ValueObservation.tracking { db in
// write access allowed
...
}
observation.requiresWriteAccess = true
```
When you use a [database pool](#database-pools), don't use this flag unless you really need it. Observations with write access are less efficient because they block all writes for the whole duration of a fetch.
## DatabaseRegionObservation
**DatabaseRegionObservation tracks changes in database [requests](#requests), and notifies each impactful [transaction](#transactions-and-savepoints).**