Combine框架中Subscriber的Auto Cancel测试

官方文档原话:

AnyCancellable

A type-erasing cancellable object that executes a provided closure when canceled.
Subscriber implementations can use this type to provide a “cancellation token” that makes it possible for a caller to cancel a publisher, but not to use the Subscription object to request items.

An Cancellable instance automatically calls when deinitialized.

测试:

import UIKit
import Combine

let subject = CurrentValueSubject(0)

var testAutoCancel = {
    //出了作用域时自动取消订阅
    var subsA = subject.sink { (value) in
        print("subsA: \(value)")
    }
    subject.send(1)
}
testAutoCancel()

subject.send(2)
//手动取消订阅后,不再收到element
var subsB = subject.sink { (value) in
     print("subsB: \(value)")
 }

class Subs {
    var subsD: AnyCancellable?
    var subsE = AnySubscriber()
    init() {
        //出了作用域时自动取消订阅
        subject.sink { (value) in
            print("subsC: \(value)")
        }
        //Subs对象销毁时自动取消订阅
        subsD = subject.sink(receiveValue: { (value) in
            print("subsD: \(value)")
        })
        subject.receive(subscriber: subsE)
    }
}
var subs: Subs? = Subs()

subject.send(3)
subsB.cancel()
subs = nil
subject.send(4)

打印:

subsA: 0
subsA: 1
subsB: 2
subsC: 2
subsD: 2
subsB: 3
subsD: 3

你可能感兴趣的:(Combine框架中Subscriber的Auto Cancel测试)