Redo ReloadingContent with @ObservedObject

Proper way to listen to changes in elements is observing their
parent.
This commit is contained in:
Davide De Rosa 2022-04-19 19:33:40 +02:00
parent 923ea923ab
commit 17a383bc9c
4 changed files with 20 additions and 8 deletions

View File

@ -25,10 +25,16 @@
import SwiftUI
struct ReloadingContent<T: Equatable, Content: View>: View {
struct ReloadingContent<O: ObservableObject, T: Equatable, Content: View>: View {
@Environment(\.scenePhase) private var scenePhase
private let elements: [T]
@ObservedObject private var object: O
private let keyPath: KeyPath<O, [T]>
private var elements: [T] {
object[keyPath: keyPath]
}
private let equality: ([T], [T]) -> Bool
@ -39,12 +45,14 @@ struct ReloadingContent<T: Equatable, Content: View>: View {
@State private var localElements: [T] = []
init(
observing elements: [T],
observing object: O,
on keyPath: KeyPath<O, [T]>,
equality: @escaping ([T], [T]) -> Bool = { $0 == $1 },
reload: (() -> Void)? = nil,
@ViewBuilder content: @escaping ([T]) -> Content
) {
self.elements = elements
self.object = object
self.keyPath = keyPath
self.equality = equality
self.reload = reload
self.content = content
@ -61,7 +69,8 @@ struct ReloadingContent<T: Equatable, Content: View>: View {
}
var body: some View {
Group {
debugChanges()
return Group {
content(localElements)
// }.onAppear {
// localElements = elements

View File

@ -90,7 +90,8 @@ struct DonateView: View {
.xxxThemeTruncation()
) {
ReloadingContent(
observing: productManager.donations,
observing: productManager,
on: \.donations,
equality: {
Set($0.map(\.productIdentifier)) == Set($1.map(\.productIdentifier))
},

View File

@ -54,7 +54,8 @@ extension OrganizerView {
var body: some View {
debugChanges()
return ReloadingContent(
observing: profileManager.headers,
observing: profileManager,
on: \.headers,
equality: {
Set($0) == Set($1)
}

View File

@ -105,7 +105,8 @@ extension PaywallView {
footer: Text(L10n.Paywall.Sections.Products.footer)
) {
ReloadingContent(
observing: productManager.products,
observing: productManager,
on: \.products,
equality: {
Set($0.map(\.productIdentifier)) == Set($1.map(\.productIdentifier))
},