Skip to content

Commit

Permalink
Document object did change (#195)
Browse files Browse the repository at this point in the history
* Change objectDidChange public API to AnyPublisher
* Add example and note that objectWillChange and objectDidChange are always paired to documentation
  • Loading branch information
jessegrosjean authored Jul 21, 2024
1 parent 410b1d1 commit 9548e39
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions Sources/Automerge/Document.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,30 @@ public final class Document: @unchecked Sendable {
try work()
}
#endif

#if canImport(Combine)
/// A publisher that sends a signal after the document is updated.
private let objectDidChangeSubject: PassthroughSubject<(), Never> = .init()

/// A publisher that emits after the document has changed.
///
/// This publisher and ``objectWillChange()`` are always paired. Unlike that
/// publisher, this one fires after the document update is complete, allowing you to
/// read any changed values.
///
/// You can use the signal from this publisher to read the and record ``Document/heads()``
/// to get the state indicator of the document after the change is complete.
public let objectDidChange: PassthroughSubject<Void, Never> = .init()
/// An example that uses this publisher to observe granular patch changes:
///
/// ```swift
/// var observedHeads = doc.heads()
/// doc.objectDidChange.sink {
/// let changes = doc.difference(since: observedHeads)
/// observedHeads = doc.heads()
/// if !changes.isEmpty {
/// processChanges(changes)
/// }
/// }.store(in: &cancellables)
public lazy var objectDidChange: AnyPublisher<(), Never> = {
objectDidChangeSubject.eraseToAnyPublisher()
}()
#endif

var reportingLogLevel: LogVerbosity
Expand Down Expand Up @@ -1272,7 +1289,7 @@ extension Document: ObservableObject {
}

fileprivate func sendObjectDidChange() {
objectDidChange.send()
objectDidChangeSubject.send()
}
}
#else
Expand Down

0 comments on commit 9548e39

Please sign in to comment.