You have 2 problems here:
1. like @matt said, your publisher isn’t living long enough. You can either store the AnyCancellable
as an instance var
, or what I like to do (and appears to be a redux best practice) is use store(in:)
to a Set<AnyCancellable>
to keep it around and have it automatically cleaned up when the object is dealloced.
2. In order to kick off the actual network request you need to sink
or assign
the value.
So, putting these together:
var cancellableSet: Set<AnyCancellable> = []
func getMyResponse() {
URLSession.shared.dataTaskPublisher(for : request).map{ a in
return a.data
}
.decode(type: MyResponse.self, decoder: JSONDecoder())
.receive(on: DispatchQueue.main)
.replaceError(with: MyResponse())
.sink { myResponse in print(myResponse) }
.store(in: &cancellableSet)
}