You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift Combine中cancellable与urlSession变量的作用及声明疑问

Combine示例中cancellable与urlSession的说明

一、urlSession的声明与作用

  • 声明位置:苹果文档示例省略了基础声明,实际开发中需要自行创建URLSession实例,常见写法有两种:
    • 使用系统共享会话:let urlSession = URLSession.shared
    • 自定义配置会话:let urlSession = URLSession(configuration: .default)
  • 作用:作为网络请求的核心载体,dataTaskPublisher(for:)是Combine为URLSession扩展的方法,能把传统的网络数据任务包装成Combine的Publisher,用来输出请求的响应和数据。

二、cancellable的声明与作用

  • 声明位置:需要在订阅的作用域内声明(比如类的实例属性、全局变量),常见写法:
    • 单个订阅:var cancellable: AnyCancellable?
    • 多个订阅:var cancellables = Set<AnyCancellable>()(配合.store(in: &cancellables)使用)
  • 核心作用:持有订阅关系。Combine的Publisher只有在调用sink/assign完成订阅后才会执行任务,AnyCancellable会保存这个订阅的引用。如果没有这个持有,订阅会在代码执行结束后立即被释放,网络请求会直接取消,无法拿到结果。
  • 额外功能:可以主动调用cancellable?.cancel()取消订阅,或者通过置空变量的方式自动释放订阅。

补充完整示例代码

import Combine
import Foundation

struct User: Codable {
    let name: String
    let userID: String
}

// 声明urlSession实例
let urlSession = URLSession.shared
// 声明cancellable变量(类中建议作为实例属性)
var cancellable: AnyCancellable?

let url = URL(string: "https://example.com/endpoint")!

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).") })

内容的提问来源于stack exchange,提问作者Avicii4ever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 05:52:43