Skip to content

Commit

Permalink
Merge pull request #6 from thoughtbot/remove-observer-is-ready
Browse files Browse the repository at this point in the history
Remove ViewModelObserver.isReadyForUpdates
  • Loading branch information
sharplet authored Aug 16, 2020
2 parents 10bedc2 + 3647532 commit 805bc33
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 33 deletions.
24 changes: 8 additions & 16 deletions Sources/CombineViewModel/ViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,35 +32,27 @@ public struct ViewModel<Object: ObservableObject> {

observer[keyPath: storageKeyPath].object = newValue

var observations: AnyPublisher<(Object, Observer?), Never>!

let checkObserverReady: (Object) -> (Object, Observer?) = { [weak observer] object in
if let observer = observer, observer.isReadyForUpdates {
return (object, observer)
} else {
return (object, nil)
}
}
var objectDidChange: AnyPublisher<(), Never>!

#if canImport(UIKit)
if let viewController = observer as? UIViewController {
dispatchPrecondition(condition: .onQueue(.main))
_combinevm_hook_viewDidLoad(viewController)

observations = newValue.observe(on: DispatchQueue.main)
.combineLatest(viewController.viewDidLoadPublisher) { object, _ in checkObserverReady(object) }
objectDidChange = newValue.observe(on: DispatchQueue.main)
.combineLatest(viewController.viewDidLoadPublisher) { _, _ in }
.eraseToAnyPublisher()
}
#endif

if observations == nil {
observations = newValue.observe(on: DispatchQueue.main)
.map(checkObserverReady)
if objectDidChange == nil {
objectDidChange = newValue.observe(on: DispatchQueue.main)
.map { _ in }
.eraseToAnyPublisher()
}

observations
.sink { _, observer in observer?.updateView() }
objectDidChange
.sink { [weak observer] in observer?.updateView() }
.store(in: &observer.subscriptions)
}
}
Expand Down
17 changes: 0 additions & 17 deletions Sources/CombineViewModel/ViewModelObserver.swift
Original file line number Diff line number Diff line change
@@ -1,23 +1,6 @@
import Combine

public protocol ViewModelObserver: AnyObject {
var isReadyForUpdates: Bool { get }
var subscriptions: Set<AnyCancellable> { get set }
func updateView()
}

extension ViewModelObserver {
public var isReadyForUpdates: Bool {
true
}
}

#if canImport(UIKit)
import UIKit

extension UIViewController {
@objc open var isReadyForUpdates: Bool {
isViewLoaded
}
}
#endif

0 comments on commit 805bc33

Please sign in to comment.