Documentation for Combine support

This commit is contained in:
Gwendal Roué committed 2020-06-25 21:24:17 +02:00
1 parent 7066980f7b
commit a193ac1474
11 files changed
+359 -40

No files matched your search

-11
View File
@@ -82,7 +82,6 @@ The ideas, in alphabetical order:
- [JSON]
- [Linux]
- [More SQL Generation]
- [Reactive Database Observation]
- [SQL Console in the Debugger]
- [SQLCipher in a Shared App Container]
- [Typed Expressions]
@@ -247,15 +246,6 @@ There are several SQLite features that GRDB could natively support:
See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations.
### Reactive Database Observation
:baby: Starter Task
We already have the [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries.
More choices of reactive engines would help more developers enjoy GRDB.
### SQL Console in the Debugger
:question: Unknown Difficulty :hammer: Tooling
@@ -319,7 +309,6 @@ Features that blur this focus are non-goals:
[JSON]: #json
[Linux]: #linux
[More SQL Generation]: #more-sql-generation
[Reactive Database Observation]: #reactive-database-observation
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
[Non-Goals]: #non-goals
[Report Bugs]: #report-bugs
+316
View File
@@ -0,0 +1,316 @@
GRDB ❤️ Combine
===============
**On systems supporting the Combine framework, GRDB offers the ability to publish database values and events using Combine's publishers.**
- [Usage]
- [Demo Application]
- [Asynchronous Database Access]
- [Database Observation]
## Usage
To connect to the database, please refer to [Database Connections].
<details>
<summary><strong>Asynchronously read from the database</strong></summary>
This publisher reads a single value and delivers it.
```swift
// DatabasePublishers.Read<[Player]>
let players = dbQueue.readPublisher { db in
try Player.fetchAll(db)
}
```
</details>
<details>
<summary><strong>Asynchronously write in the database</strong></summary>
This publisher updates the database and delivers a single value.
```swift
// DatabasePublishers.Write<Void>
let write = dbQueue.writePublisher { db in
try Player(...).insert(db)
}
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher { db -> Int in
try Player(...).insert(db)
return try Player.fetchCount(db)
}
```
</details>
<details>
<summary><strong>Observe changes in database values</strong></summary>
This publisher delivers fresh values whenever the database changes:
```swift
// A publisher with output [Player] and failure Error
let publisher = ValueObservation
.tracking { db in try Player.fetchAll(db) }
.publisher(in: dbQueue)
// A publisher with output Int? and failure Error
let publisher = ValueObservation
.tracking { db in try Int.fetchOne(db, sql: "SELECT MAX(score) FROM player") }
.publisher(in: dbQueue)
```
</details>
<details>
<summary><strong>Observe database transactions</strong></summary>
This publisher delivers database connections whenever a database transaction has impacted an observed region:
```swift
// A publisher with output Database and failure Error
let publisher = DatabaseRegionObservation
.tracking(Player.all())
.publisher(in: dbQueue)
let cancellable = publisher.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Exclusive write access to the database after players have been impacted")
})
// A publisher with output Database and failure Error
let publisher = DatabaseRegionObservation
.tracking(SQLRequest<Int>(sql: "SELECT MAX(score) FROM player"))
.publisher(in: dbQueue)
let cancellable = publisher.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Exclusive write access to the database after maximum score has been impacted")
})
```
</details>
# Asynchronous Database Access
GRDB provide publishers that perform asynchronous database accesses.
- [`readPublisher(receiveOn:value:)`]
- [`writePublisher(receiveOn:updates:)`]
- [`writePublisher(receiveOn:updates:thenRead:)`]
#### `DatabaseReader.readPublisher(receiveOn:value:)`
This methods returns a publisher that completes after database values have been asynchronously fetched.
```swift
// DatabasePublishers.Read<[Player]>
let players = dbQueue.readPublisher { db in
try Player.fetchAll(db)
}
```
Any attempt at modifying the database completes subscriptions with an error.
When you use a [database queue] or a [database snapshot], the read has to wait for any eventual concurrent database access performed by this queue or snapshot to complete.
When you use a [database pool], reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured].
This publisher can be subscribed from any thread. A new database access starts on every subscription.
The fetched value is published on the main queue, unless you provide a specific scheduler to the `receiveOn` argument.
#### `DatabaseWriter.writePublisher(receiveOn:updates:)`
This method returns a publisher that completes after database updates have been successfully executed inside a database transaction.
```swift
// DatabasePublishers.Write<Void>
let write = dbQueue.writePublisher { db in
try Player(...).insert(db)
}
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher { db -> Int in
try Player(...).insert(db)
return try Player.fetchCount(db)
}
```
This publisher can be subscribed from any thread. A new database access starts on every subscription.
It completes on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
When you use a [database pool], and your app executes some database updates followed by some slow fetches, you may profit from optimized scheduling with [`writePublisher(receiveOn:updates:thenRead:)`]. See below.
#### `DatabaseWriter.writePublisher(receiveOn:updates:thenRead:)`
This method returns a publisher that completes after database updates have been successfully executed inside a database transaction, and values have been subsequently fetched:
```swift
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher(
updates: { db in try Player(...).insert(db) }
thenRead: { db, _ in try Player.fetchCount(db) })
}
```
It publishes exactly the same values as [`writePublisher(receiveOn:updates:)`]:
```swift
// DatabasePublishers.Write<Int>
let newPlayerCount = dbQueue.writePublisher { db -> Int in
try Player(...).insert(db)
return try Player.fetchCount(db)
}
```
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from a function to the other (it is ignored in the sample code above).
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention. See [Advanced DatabasePool](../README.md#advanced-databasepool) for more information.
When you use a [database queue], the results are guaranteed to be identical, but no scheduling optimization is applied.
This publisher can be subscribed from any thread. A new database access starts on every subscription.
It completes on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
# Database Observation
Database Observation publishers are based on [ValueObservation] and [DatabaseRegionObservation]. Please refer to their documentation for more information. If your application needs change notifications that are not built as Combine publishers, check the general [Database Changes Observation] chapter.
- [`ValueObservation.publisher(in:scheduling:)`]
- [`DatabaseRegionObservation.publisher(in:)`]
#### `ValueObservation.publisher(in:scheduling:)`
[ValueObservation] tracks changes in database values. You can turn it into a Combine publisher:
```swift
let observation = ValueObservation.tracking { db in
try Player.fetchAll(db)
}
// A publisher with output [Player] and failure Error
let publisher = observation.publisher(in: dbQueue)
```
This publisher has the same behavior as ValueObservation:
- It notifies an initial value before the eventual changes.
- It may coalesce subsequent changes into a single notification.
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](../README.md#valueobservationremoveduplicates) GRDB operator also.
- It stops emitting any value after the database connection is closed. But it never completes.
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservation scheduler](../README.md#valueobservation-scheduling).
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
```swift
// Immediate notification of the initial value
let cancellable = observation
.publisher(
in: dbQueue,
scheduling: .immediate) // <-
.sink(
receiveCompletion: { completion in ... },
receiveValue: { (players: [Player]) in print("Fresh players: \(players)") })
// <- here "fresh players" is already printed.
```
Note that the `.immediate` scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise.
See [ValueObservation Scheduling](../README.md#valueobservation-scheduling) for more information.
:warning: **ValueObservation and Data Consistency**
When you compose ValueObservation publishers together with the [combineLatest](https://developer.apple.com/documentation/combine/publisher/3333677-combinelatest) operator, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
Instead, compose requests together into **one single** ValueObservation, as below (this is the technique used in the [Demo Application]):
```swift
// DATA CONSISTENCY GUARANTEED
let hallOfFamePublisher = ValueObservation
.tracking { db -> HallOfFame in
let playerCount = try Player.fetchCount(db)
let bestPlayers = try Player.limit(10).orderedByScore().fetchAll(db)
return HallOfFame(playerCount:playerCount, bestPlayers:bestPlayers)
}
.publisher(in: dbQueue)
```
See [ValueObservation] for more information.
#### `DatabaseRegionObservation.publisher(in:)`
[DatabaseRegionObservation] notifies all transactions that impact a tracked database region. You can turn it into a Combine publisher:
```swift
let request = Player.all()
let observation = DatabaseRegionObservation.tracking(request)
// A publisher with output Database and failure Error
let publisher = observation.publisher(in: dbQueue)
```
This publisher can be created and subscribed from any thread. It delivers database connections in a "protected dispatch queue", serialized with all database updates. It only completes when a database error happens.
```swift
let request = Player.all()
let cancellable = DatabaseRegionObservation
.tracking(request)
.publisher(in: dbQueue)
.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Players have changed.")
})
try dbQueue.write { db in
try Player(name: "Arthur").insert(db)
try Player(name: "Barbara").insert(db)
}
// Prints "Players have changed."
try dbQueue.write { db in
try Player.deleteAll(db)
}
// Prints "Players have changed."
```
See [DatabaseRegionObservation] for more information.
[Database Connections]: ../README.md#database-connections
[Usage]: #usage
[Asynchronous Database Access]: #asynchronous-database-access
[Combine]: https://developer.apple.com/documentation/combine
[Database Changes Observation]: ../README.md#database-changes-observation
[Database Observation]: #database-observation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[Demo Application]: Documentation/Demo/README.md
[SQLite]: http://sqlite.org
[ValueObservation]: ../README.md#valueobservation
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
[configured]: ../README.md#databasepool-configuration
[database pool]: ../README.md#database-pools
[database queue]: ../README.md#database-queues
[database snapshot]: ../README.md#database-snapshots
[scheduler]: https://developer.apple.com/documentation/combine/scheduler
@@ -341,7 +341,5 @@ try controller.performFetch()
[ValueObservation]: ../README.md#valueobservation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[FetchableRecord]: ../README.md#fetchablerecord-protocol
[TableRecord]: ../README.md#tablerecord-protocol
+25 -4
View File
@@ -6,6 +6,7 @@ Migrating From GRDB 4 to GRDB 5
- [Preparing the Migration to GRDB 5](#preparing-the-migration-to-grdb-5)
- [New requirements](#new-requirements)
- [ValueObservation](#valueobservation)
- [Combine Integration](#combine-integration)
- [Other Changes](#other-changes)
@@ -34,7 +35,7 @@ GRDB requirements have been bumped:
[ValueObservation] is the database observation tool that tracks changes in database values. It has quite changed in GRDB 5.
Those changes have the vanilla GRDB, [GRDBCombine], and [RxGRDB], offer a common API, and a common behavior. This greatly helps choosing or switching your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
Those changes have the vanilla GRDB, its [Combine publishers], and [RxGRDB] offer a common API, and a common behavior. This greatly helps choosing or switching your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
In the end, this migration step might require some work. But it's for the benefit of all!
@@ -188,7 +189,7 @@ The changes can quite impact your application. We'll describe them below, as wel
Note that the `.immediate` scheduling requires that the observation starts from the main thread. A fatal error is raised otherwise.
<details>
<summary>GRDBCombine impact</summary>
<summary>Combine impact</summary>
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
@@ -262,7 +263,7 @@ The changes can quite impact your application. We'll describe them below, as wel
1. ValueObservation used to have a `compactMap` method. This method has been removed without any replacement.
If your application uses GRDBCombine or RxGRDB, then use the `compactMap` method from Combine or RxSwift instead.
If your application uses Combine publishers or RxGRDB, then use the `compactMap` method from Combine or RxSwift instead.
2. ValueObservation used to have a `combine` method. This method has been removed without any replacement.
@@ -293,6 +294,26 @@ The changes can quite impact your application. We'll describe them below, as wel
As is previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
## Combine Integration
GRDB 4 had a companion library named GRDBCombine. Combine support is now embedded right into GRDB, and you have to remove any dependency on GRDBCombine.
GRDBCombine used to define a `fetchOnSubscription()` method of the ValueObservation subscriber. It has been removed. Replace it with `scheduling: .immediate` for the same effect (an initial value is notified immediately, synchronously, when the publisher is subscribed):
```swift
// BEFORE: GRDB 4 + GRDBCombine
let observation = ValueObservation.tracking { db in ... }
let publisher = observation
.publisher(in: dbQueue)
.fetchOnSubscription()
// NEW: GRDB 5
let observation = ValueObservation.tracking { db in ... }
let publisher = observation
.publisher(in: dbQueue, scheduling: .immediate)
```
## Other Changes
1. The `Configuration.trace` property has been removed. You know use the `Database.trace(options:_:)` method instead:
@@ -429,7 +450,6 @@ The changes can quite impact your application. We'll describe them below, as wel
[ValueObservation]: ../README.md#valueobservation
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[GRDBCombine]: http://github.com/groue/GRDBCombine
[Observing a Varying Database Region]: ../README.md#observing-a-varying-database-region
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
[Custom SQL functions]: ../README.md#custom-sql-functions
@@ -438,3 +458,4 @@ The changes can quite impact your application. We'll describe them below, as wel
[SQLLiteral]: SQLInterpolation.md#sqlliteral
[SQLRequest]: ../README.md#custom-requests
[QueryInterfaceRequest]: ../README.md#requests
[Combine publishers]: Combine.md
@@ -679,7 +679,7 @@ Instead, have a look at [Database Observation]:
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
>
> :bulb: **Tip**: [GRDBCombine] performs automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
> :bulb: **Tip**: [Combine Support] allows automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
>
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
>
@@ -710,7 +710,6 @@ Instead, have a look at [Database Observation]:
[Database Observation]: ../README.md#database-changes-observation
[ValueObservation]: ../README.md#valueobservation
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[GRDBCombine]: http://github.com/groue/GRDBCombine
[TransactionObserver]: ../README.md#transactionobserver-protocol
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
@@ -727,3 +726,4 @@ Instead, have a look at [Database Observation]:
[Association Aggregates]: AssociationsBasics.md#association-aggregates
[Codable Record]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Combine Support]: Combine.md
+2 -2
View File
@@ -254,7 +254,7 @@ See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for
## How to perform cross-process database observation
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify database changes performed by other processes.
GRDB [Database Observation] features, as well as its [Combine publishers] and [RxGRDB], are not able to notify database changes performed by other processes.
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
@@ -280,10 +280,10 @@ let observer = try observation.start(in: dbPool) { (db: Database) in
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
[Database Pool]: ../README.md#database-pools
[Database Observation]: ../README.md#database-changes-observation
[GRDBCombine]: http://github.com/groue/GRDBCombine
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[WAL mode]: https://www.sqlite.org/wal.html
[How do I monitor the duration of database statements execution?]: ../README.md#how-do-i-monitor-the-duration-of-database-statements-execution
[Combine publishers]: Combine.md
+4 -8
View File
@@ -117,7 +117,7 @@ let players = try Player.fetchAll(db)
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, or by observing database changes and react accordingly.
In order to keep your views synchronized with the database content, you can use [ValueObservation]. It notifies fresh values after each database change. The [GRDBCombine] and [RxGRDB] companion libraries provide support for [Combine] and [RxSwift].
In order to keep your views synchronized with the database content, you can use [ValueObservation]. It notifies fresh values after each database change, with convenient support for [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB).
```swift
/// An observation of [Player]
@@ -130,7 +130,7 @@ let cancellable = observation.start(in: dbQueue,
onError: { error in ... },
onChange: { (players: [Player]) in print("Fresh players") })
// GRDBCombine
// GRDB + Combine
let cancellable = observation.publisher(in: dbQueue).sink(
receiveCompletion: { completion in ... },
receiveValue: { (players: [Player]) in print("Fresh players") })
@@ -254,14 +254,14 @@ extension Player {
let player = try Player.filter(name: "Arthur O'Brien").fetchOne(db)
```
Custom SQL requests as the one above are welcome in database observation tools like the built-in [ValueObservation], or the companion libraries [GRDBCombine] and [RxGRDB]:
Custom SQL requests as the one above are welcome in database observation tools like the built-in [ValueObservation] and its [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB) flavors:
```swift
let playerObservation = ValueObservation.tracking { db in
try Player.filter(name: "Arthur O'Brien").fetchOne(db)
}
// Observe the SQL request with GRDBCombine
// Observe the SQL request with Combine
let cancellable = playerObservation.publisher(in: dbQueue).sink(
receiveCompletion: { completion in ... },
receiveValue: { (player: Player?) in print("Player has changed") })
@@ -300,10 +300,6 @@ Happy GRDB! :gift:
[PersistableRecord]: ../README.md#records
[Realm]: http://realm.io
[FetchableRecord]: ../README.md#records
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[RxSwift]: https://github.com/ReactiveX/RxSwift
[GRDBCombine]: http://github.com/groue/GRDBCombine
[Combine]: https://developer.apple.com/documentation/combine
[SQLite.swift]: http://github.com/stephencelis/SQLite.swift
[StORM]: https://www.perfect.org/docs/StORM.html
[Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery
+1 -1
View File
@@ -11,7 +11,7 @@ import Foundation
/// that it starts producing its value on demand, **synchronously**, and that
/// it produces its value on promise completion, **synchronously**.
///
/// Both two extra scheduling guarantees are used by GRDBCombine in order to be
/// Both two extra scheduling guarantees are used by GRDB in order to be
/// able to spawn concurrent database reads right from the database writer
/// queue, and fulfill GRDB preconditions.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
+1 -1
View File
@@ -8,7 +8,7 @@ import Foundation
/// Unlike Combine's Publishers.ReceiveOn, ReceiveValuesOn only re-schedule
/// values and completion. It does not re-schedule subscription.
///
/// This scheduling guarantee is used by GRDBCombine in order to be able
/// This scheduling guarantee is used by GRDB in order to be able
/// to make promises on the scheduling of database values without surprising
/// the users as in https://forums.swift.org/t/28631.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
+7 -8
View File
@@ -72,13 +72,13 @@ GRDB ships with:
- [WAL Mode Support](#database-pools): Extra performance for multi-threaded applications.
- [Migrations]: Transform your database as your application evolves.
- [Database Observation](#database-changes-observation): Observe database changes and transactions.
- [Combine Support]: Access and observe the database with Combine publishers.
- [Full-Text Search]
- [Encryption](#encryption)
- [Support for Custom SQLite Builds](Documentation/CustomSQLiteBuilds.md)
Companion libraries that enhance and extend GRDB:
- [GRDBCombine]: track database changes in a reactive way, with [Combine](https://developer.apple.com/documentation/combine).
- [RxGRDB]: track database changes in a reactive way, with [RxSwift](https://github.com/ReactiveX/RxSwift).
- [GRDBObjc](https://github.com/groue/GRDBObjc): FMDB-compatible bindings to GRDB.
@@ -5178,7 +5178,7 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas
- [ValueObservation]: Track changes of database values.
- [DatabaseRegionObservation]: Tracking transactions that impact a database region.
- [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation.
- [GRDBCombine]: Automated tracking of database changes, with [Combine](https://developer.apple.com/documentation/combine).
- [Combine Support]: Automated tracking of database changes, with [Combine].
- [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift).
Database observation requires that a single [database queue](#database-queues) or [pool](#database-pools) is kept open for all the duration of the database usage.
@@ -5334,15 +5334,14 @@ Tracked changes include changes performed by the [query interface](#the-query-in
cancellable.cancel()
```
**As a convenience**, the two companion libraries [GRDBCombine] and [RxGRDB] bring Combine and RxSwift support to ValueObservation:
**As a convenience**, ValueObservation can be turned into a Combine publisher, or a RxSwift Observable (see [Combine Support] and the companion library [RxGRDB]):
<details>
<summary>GRDBCombine example</summary>
<summary>Combine example</summary>
```swift
import Combine
import GRDB
import GRDBCombine
let observation = ValueObservation.tracking(Player.fetchAll)
@@ -5895,7 +5894,7 @@ do {
> :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument.
[DatabaseRegionObservation], [ValueObservation], [GRDBCombine], and [RxGRDB] are all based on the TransactionObserver protocol.
[DatabaseRegionObservation], [ValueObservation], [Combine Support], and [RxGRDB] are all based on the TransactionObserver protocol.
See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter.
@@ -7134,7 +7133,7 @@ These protocols provide a unified API that let you write generic code that targe
- [Migrations]
- [DatabaseRegionObservation]
- [ValueObservation]
- [GRDBCombine]
- [Combine Support]
- [RxGRDB]
Only five types adopt those protocols: DatabaseQueue, DatabasePool, DatabaseSnapshot, AnyDatabaseReader, and AnyDatabaseWriter. Expanding this set is not supported: any future GRDB release may break your custom writers and readers, without notice.
@@ -7847,12 +7846,12 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
[ValueObservation]: #valueobservation
[DatabaseRegionObservation]: #databaseregionobservation
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
[GRDBCombine]: http://github.com/groue/GRDBCombine
[DatabaseRegionConvertible]: #the-databaseregionconvertible-protocol
[DatabaseRegion]: #databaseregion
[SQL Interpolation]: Documentation/SQLInterpolation.md
[custom SQLite build]: Documentation/CustomSQLiteBuilds.md
[Combine]: https://developer.apple.com/documentation/combine
[Combine Support]: Documentation/Combine.md
[Demo Application]: Documentation/DemoApps/GRDBDemoiOS/README.md
[Sharing a Database]: Documentation/SharingADatabase.md
[FAQ]: #faq
+1 -1
View File
@@ -25,7 +25,7 @@ final class Test<Context> {
func runInTemporaryDirectory(context: (_ directoryURL: URL) throws -> Context) throws -> Self {
for _ in 1...repeatCount {
let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent("GRDBCombine", isDirectory: true)
.appendingPathComponent("GRDB", isDirectory: true)
.appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString, isDirectory: true)
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)