Nor*_*Lim 4 swift swiftui combine
我的应用程序具有收藏对象的功能。有多个视图需要访问才能[Favorite]
呈现 UI 以及添加和删除它们。
我想要一个单一来源[Favorite]
:
UserDefaults
我尝试使用@Binding
链接源,但当源更改时它不会更新 UI。
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)
})
}
}
Run Code Online (Sandbox Code Playgroud)
Publishers
我还尝试使用and创建绑定,Subscribers
但这最终导致无限循环。
提前致谢
这是可能的方法。使用 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)
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1482 次 |
最近记录: |