Skip to content

Instantly share code, notes, and snippets.

@Obbut
Created January 12, 2021 19:11
Show Gist options
  • Select an option

  • Save Obbut/b270369eb8134708d4092d86d2163ee4 to your computer and use it in GitHub Desktop.

Select an option

Save Obbut/b270369eb8134708d4092d86d2163ee4 to your computer and use it in GitHub Desktop.

Revisions

  1. Obbut revised this gist Jan 12, 2021. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions ObjectDidChangePublisher.swift
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    import Combine
    import Foundation

    @available(iOS 13.0, macOS 10.15, tvOS 13, watchOS 5, *)
    @available(iOS 13.0, macOS 10.15, tvOS 13, watchOS 6, *)
    public struct ObjectDidChangePublisher<ObjectWillChangePublisher: Publisher>: Publisher {
    private let upstream: ObjectWillChangePublisher
    public typealias Output = ObjectWillChangePublisher.Output
    @@ -18,7 +18,7 @@ public struct ObjectDidChangePublisher<ObjectWillChangePublisher: Publisher>: Pu
    }
    }

    @available(iOS 13.0, macOS 10.15, tvOS 13, watchOS 5, *)
    @available(iOS 13.0, macOS 10.15, tvOS 13, watchOS 6, *)
    extension ObservableObject {
    public var objectDidChange: ObjectDidChangePublisher<ObjectWillChangePublisher> {
    ObjectDidChangePublisher(upstream: objectWillChange)
  2. Obbut created this gist Jan 12, 2021.
    26 changes: 26 additions & 0 deletions ObjectDidChangePublisher.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    import Combine
    import Foundation

    @available(iOS 13.0, macOS 10.15, tvOS 13, watchOS 5, *)
    public struct ObjectDidChangePublisher<ObjectWillChangePublisher: Publisher>: Publisher {
    private let upstream: ObjectWillChangePublisher
    public typealias Output = ObjectWillChangePublisher.Output
    public typealias Failure = ObjectWillChangePublisher.Failure

    fileprivate init(upstream: ObjectWillChangePublisher) {
    self.upstream = upstream
    }

    public func receive<S>(subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
    self.upstream
    .receive(on: DispatchQueue.main) /// This essentially just delays the publisher until after the `willSet` property observer. Published property changes must happen on the main thread anyway.
    .receive(subscriber: subscriber)
    }
    }

    @available(iOS 13.0, macOS 10.15, tvOS 13, watchOS 5, *)
    extension ObservableObject {
    public var objectDidChange: ObjectDidChangePublisher<ObjectWillChangePublisher> {
    ObjectDidChangePublisher(upstream: objectWillChange)
    }
    }