Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

iOS Combine framework @Published doesnt capture post modification values

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading