I'm trying to get my grips on the Combine framework from Apple and I'm unsure if I'm doing it right. I have the below error in my code. Can anybody please suggest how to get around this? Many thanks
Error: Escaping closure captures mutating 'self' parameter
import Combine
import Foundation
// Model
protocol Fetchable {
associatedtype T: Decodable
var foo: [T] { get set }
}
extension Fetchable {
internal mutating func fetch(
from url: URL
) {
let _: AnyCancellable? = URLSession.shared
.dataTaskPublisher(for: url)
.map({ $0.data })
.decode(type: Self.T.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("Received completion: ", completion)
break
case .failure(let error):
print("Received completion: ", completion, error)
}
}, receiveValue: { value in // Escaping closure captures mutating 'self' parameter
print(".sink() received \(value)")
self.foo.insert(value, at: 0) // Captured here
})
}
}
struct MyDecodableType: Codable {
...
}
// ViewModel
class MyClass: ObservableObject, Fetchable {
@Published internal var foo: [MyDecodableType] = []
}