admin管理员组

文章数量:1287605

So I having a trouble when reading the Convert incoming raw data to your types with Combine operators section of Processing URL session data task results with Combine article.

Here is the template from the section, and I couldn't find where the cancellable and urlSession variable declared or their purpose.

struct User: Codable {
    let name: String
    let userID: String
}
let url = URL(string: ";)!

//Where are these two variables coming from and going?
cancellable = urlSession

    .dataTaskPublisher(for: url)
    .tryMap() { element -> Data in
        guard let httpResponse = element.response as? HTTPURLResponse,
            httpResponse.statusCode == 200 else {
                throw URLError(.badServerResponse)
            }
        return element.data
        }
    .decode(type: User.self, decoder: JSONDecoder())
    .sink(receiveCompletion: { print ("Received completion: \($0).") },
          receiveValue: { user in print ("Received user: \(user).")})
Retry transient errors and catch and replace persistent errors

So I having a trouble when reading the Convert incoming raw data to your types with Combine operators section of Processing URL session data task results with Combine article.

Here is the template from the section, and I couldn't find where the cancellable and urlSession variable declared or their purpose.

struct User: Codable {
    let name: String
    let userID: String
}
let url = URL(string: "https://example/endpoint")!

//Where are these two variables coming from and going?
cancellable = urlSession

    .dataTaskPublisher(for: url)
    .tryMap() { element -> Data in
        guard let httpResponse = element.response as? HTTPURLResponse,
            httpResponse.statusCode == 200 else {
                throw URLError(.badServerResponse)
            }
        return element.data
        }
    .decode(type: User.self, decoder: JSONDecoder())
    .sink(receiveCompletion: { print ("Received completion: \($0).") },
          receiveValue: { user in print ("Received user: \(user).")})
Retry transient errors and catch and replace persistent errors
Share Improve this question edited Feb 24 at 5:42 Avicii4ever asked Feb 23 at 13:50 Avicii4everAvicii4ever 1531 silver badge10 bronze badges 6
  • 1 Look at this which will explain you the basic principles f combine with urlsession and json decoding – Ptit Xav Commented Feb 23 at 15:02
  • 1 You're cancelling your subscription almost immediately, so this will never fire correctly. The typical pattern is to store the subscription in an cancellables: Set<AnyCancellable> owned by the relevant view, so that when the view disappears, you cancel any outstanding network operations whose results you no longer care about.. You add your subscriptions to it via .store(in: &cancellables). medium/@viveksehrawat36/… – Alexander Commented Feb 23 at 15:03
  • Thanks for your material, sadly this post has been closed : ( – Avicii4ever Commented Feb 23 at 15:07
  • Well yeah, there really isn't a question to be answered here. If you edit read through the linked documentation and rework your post into an answerable question, people can vote to reopen it – Alexander Commented Feb 23 at 21:59
  • 1 Thanks @Rob, so this is why all materials I found said that the AnyCancellable need to be saved, great explanation! – Avicii4ever Commented Feb 26 at 6:32
 |  Show 1 more comment

1 Answer 1

Reset to default 0

The AnyCancellable returned by sink is an object on which you can call cancel()should you need to stop the asynchronous work. But, as others have noted, the documentation tells us, it is also the case that, “An AnyCancellable instance automatically calls cancel() when deinitialized.” So, we need to store that AnyCancellableinstance in some ivar (either a simple AnyCancellable or a Set<AnyCancellable> property), not a local variable. If stored in a local variable, it will immediately fall out of scope and be canceled before the asynchronous work is performed.

In short, once we store it in that property, it will conveniently stop the work when that parent object falls out of scope. But this must be a property, not just a local variable of the function.

本文标签: What does cancellable variable do in Swift Combine documentStack Overflow