Cancellable可以取消活动或者操作的协议。
public protocol Cancellable {
/// Cancel the activity.
/// Calling `cancel()` frees up any allocated resources. It also stops side effects such as timers, network access, or disk I/O.
func cancel()
}
应用场景:例如但我们进行一个网络请求,或者一个需要耗时操作时,处理过程中想要中断。或者一些临时生成的资源需要在取消订阅的时候释放。
Publisher在被订阅时会给Subscriber发送一个Subscription消息,这个Subscription恰好也实现了Cancellable协议,在取消订阅时,会调用它的cancel方法。
func cancellableFunc() {
let publisher = Future<Any, Never> { promise in
DispatchQueue.main.asyncAfter(deadline: .now()+3) {
promise(.success("执行成功"))
}
}
let cancellable = publisher.sink { completion in
print("completion: \(completion)")
} receiveValue: { receive in
print("receive: \(receive)")
}
cancellable.store(in: &subscriptions) //长久持有
cancellable.cancel()
}