首页 > 解决方案 > Combine - Assigning publisher value

问题描述

I'm sorry if this is a basic question but I'm still getting to grips with Combine.

I have a publisher that is linked to changes in CoreData.

I am trying to subscribe to those changes in my ViewModel using :

CDPublisher(
        request: Book.fetchAllBooks(),
        context: PersistentStore.shared.context
    )
    .map { $0 }
    .receive(on: DispatchQueue.main)
    .sink { [weak self] newBooks in
        self?.books = newBooks // Error here
    }
    .store(in: &cancellables)

I want to assign the new array of books newBooks to an @Published array called books of type [Book].

However I get this error:

Cannot assign value of type 'Subscribers.Completion<CDPublisher.Failure>' (aka 'Subscribers.Completion') to type '[Book]'

I believe the problem stems from my .map. I added it because without it I got this error:

Referencing instance method 'sink(receiveValue:)' on 'Publisher' requires the types 'CDPublisher.Failure' (aka 'Error') and 'Never' be equivalent

FYI the publisher I'm using is taken from: https://betterprogramming.pub/combine-publishers-and-core-data-424b68fe9473

Thanks for your help.

标签: swiftswiftuicombine

解决方案


推荐阅读