Skip to content

Instantly share code, notes, and snippets.

@kean
Last active February 23, 2020 22:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kean/9179160bffc8e063979e96f21950f662 to your computer and use it in GitHub Desktop.
Save kean/9179160bffc8e063979e96f21950f662 to your computer and use it in GitHub Desktop.
_DynamicProperty
// 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