iOS Combine framework @Published 不捕获 post 修改值

iOS Combine framework @Published doesnt capture post modification values

我注意到 sink 只被调用了一次

class StorefrontViewModel {
    @Published var page = 0
        @Published var string = "lorem ipsum"

        private var cancellableBag = Set<AnyCancellable>()

        init() {

            let publisher = $page
                .map { [unowned self] in
                    return [=12=] == 1 ? self.string.lowercased() : self.string.uppercased()
            }

            publisher
                .eraseToAnyPublisher()
                .assign(to: \.string, on: self)
                .store(in: &cancellableBag) // must store the subscriber to get the events
        }
}
    var pager = StorefrontViewModel()
        pager.$string.sink {  print([=13=])}
        pager.page = 1 // lorem ipsum
        pager.page = 2 // LOREM IPSUM
        pager.page = 3 // LOREM IPSUM
        pager.page = 4 // LOREM IPSUM
        pager.page = 1 // lorem ipsum
        pager.page = 1 // lorem ipsum

这是输出 LOREM IPSUM

想知道为什么 sink 即使我多次设置 pager.page 值也会被调用

您从未存储来自 sink 的取消标记,因此流立即被取消。以后不要忽视编译器给你的警告。