My app has the feature of favorit-ing objects. There are multiple views that require access to [Favorite]
to render UI as well as adding and removing them.
I would like to have a single source of [Favorite]
where:
UserDefaults
I attempted to use @Binding
to link the the source but it does not update UI when the source is changed.
class Singleton {
static let shared = Singleton()
var favorites = CurrentValueSubject<[Favorite], Never>(someFavorites)
}
class ViewModel: ObservableObject {
@Binding var favorites: [Favorite]
init() {
_favorites = Binding<[Favorite]>(get: { () -> [Favorite] in
Singleton.shared.favorites.value
}, set: { newValue in
Singleton.shared.favorites.send(newValue)
})
}
}
I've also attempted creating the binding using Publishers
and Subscribers
but that ends up in an infinite loop.
Thanks in advance
Here is possible approach. Tested with Xcode 11.5b2.
class Singleton {
static let shared = Singleton()
// configure set initial value as needed, [] used for testing
var favorites = CurrentValueSubject<[Favorite], Never>([])
}
class ViewModel: ObservableObject {
@Published var favorites: [Favorite] = []
private var cancellables = Set<AnyCancellable>()
init() {
Singleton.shared.favorites
.receive(on: DispatchQueue.main)
.sink { [weak self] values in
self?.favorites = values
}
.store(in: &cancellables)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With