Last active
February 23, 2020 22:47
-
-
Save kean/9179160bffc8e063979e96f21950f662 to your computer and use it in GitHub Desktop.
_DynamicProperty
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A speculative _ViewRendererHost implementation which uses Mirror (Swift reflection) to find all | |
// of the dynamic properties (`DynamicProperty`) associated with a given view (`View`), observe | |
// the changes to these properties and automatically refresh the view whenever any of these property change. | |
protocol _DynamicProperty { | |
var objectWillChange: AnyPublisher<Void, Never> { get } | |
} | |
extension ObservedObject: _DynamicProperty { | |
var objectWillChange: AnyPublisher<Void, Never> { | |
wrappedValue.objectWillChange | |
.map { _ in () } | |
.eraseToAnyPublisher() | |
} | |
} | |
final class _ViewRendederHost<View: SwiftUI.View> { | |
private let view: View | |
private var bag = [AnyCancellable]() | |
init(view: View) { | |
self.view = view | |
Mirror(reflecting: view) | |
.children | |
.compactMap { $0.value as? _DynamicProperty } | |
.forEach(subscribe(to:)) | |
} | |
private func subscribe(to property: _DynamicProperty) { | |
property.objectWillChange | |
.sink { [unowned self] _ in self.update() } | |
.store(in: &bag) | |
} | |
private func update() { | |
let body = view.body // Create a new body with the updated values | |
print(body) | |
// TODO: render body using some internal SwiftUI mechanism | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment