Home > OS >  iOS Combine framework @Published doesnt capture post modification values
iOS Combine framework @Published doesnt capture post modification values

Time:05-05

I noticed that sink is called only once

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 $0 == 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($0)}
        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

Here is the output LOREM IPSUM.

Wondering why sink is called even though I set pager.page value multiple times

CodePudding user response:

You never stored the cancellation token from sink so the stream was immediately cancelled. In the future, don't ignore the warning the compiler is giving you.

  • Related