I am trying to decode a Publisher in another file which is dataService.$data, it is:
@Published var data: Data? = nil
Before I was using a Networking manager and it returned AnyPublisher<Data, Error>
let dataDownload = NetworkingManager.download(url: url)
casaSubscription = dataService.$data
.decode(type: [House].self, decoder: XMLDecoder())
.sink(receiveCompletion: NetworkingManager.handleCompletion, receiveValue: { [weak self] (returnedCasas) in
self?.house = returnedCasas
self?.houseSubscription?.cancel()
})
Instead of dataService.$data I had dataDownload and it all worked fine, but now, I try to use dataService.$data and it throws the error below
Instance method 'decode(type:decoder:)' requires the types 'Published<Data?>.Publisher.Output' (aka 'Optional<Data>') and 'Data' be equivalent
CodePudding user response:
Optional(Data)
and Data
are not the same type.
In Combine avoid optionals as much as possible.
A simple solution is to declare an empty Data
instance
@Published var data = Data()
and filter it in the pipeline
casaSubscription = dataService.$data
.filter{!$0.isEmpty}
.decode(type: [House].self, decoder: XMLDecoder()) ...
Or – if you really want to keep the optional
casaSubscription = dataService.$data
.compactMap{$0}
.decode(type: [House].self, decoder: XMLDecoder()) ...