绑定到多个视图的单例发布者

Nor*_*Lim 4 swift swiftui combine

概述

我的应用程序具有收藏对象的功能。有多个视图需要访问才能[Favorite]呈现 UI 以及添加和删除它们。

我想要一个单一来源[Favorite]

  1. 所有视图都基于它渲染 UI
  2. 更新此源会向订阅它的所有视图发出信号,并根据更新后的值重新渲染
  3. 每次更新时,源都会保留在UserDefaults
  4. 从 UI 更新收藏夹也会更新 Singleton 的源代码,因此需要更新其他视图

尝试1

我尝试使用@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)

尝试2

Publishers我还尝试使用and创建绑定,Subscribers但这最终导致无限循环。


提前致谢

Asp*_*eri 5

这是可能的方法。使用 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)