Overview
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:
- all views render UI based on it
- updating this source signals all views subscribed to it and rerender based on the updated value
- on each update, the source is persisted in
UserDefaults - updating favorites from UI also updates the Singleton's source, therefore signally other views to update
Attempt 1
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)
})
}
}
Attempt 2
I've also attempted creating the binding using Publishers and Subscribers but that ends up in an infinite loop.
Thanks in advance