본문 바로가기
Swift

Swift: Combine(3) - Cancellable

by songmoro 2023. 11. 3.
728x90

Cancellable: A protocol indicating that an activity or action supports cancellation.(활동이나 행동이 취소를 지원한다는 것을 나타내는 프로토콜.)

protocol Cancellable

 

cancel()을 호출하면 할당된 자원이 확보됩니다(free).

더해서, 타이머, 네트워크 액세스, 디스크 I/O에서 발생하는 부작용(side effect)을 방지해 줍니다.

 

  • cancel(): 사용자 정의 Publisher를 지원할 때, Cancellable의 cancel()을 구현하여 Publisher가 downstream subscriber에게 요소를 전달하는 것을 중단시킬 수 있습니다.

 

간단하게 말하면, cancel은 subscription을 취소하기 위해 사용합니다.

class IntSubscriber {
    @Published var number: Int = 0
    
    func increaseNumber() {
        number += 1
    }
}

let intSubscriber = IntSubscriber()

// sink의 return은 AnyCancellable

let cancellable = intSubscriber.$number.sink {
    print("number is \\($0)") // number is 0
}

intSubscriber.increaseNumber() // number is 1
intSubscriber.increaseNumber() // number is 2
cancellable.cancel()
intSubscriber.increaseNumber() // x

 

 

store

store(in:): Stores this type-erasing cancellable instance in the specified set.(취소 가능한 인스턴스를 지정된 세트에 저장합니다.)

final func store(in set: inout Set<AnyCancellable>)

 

store는 여러 subscription을 관리하기 위해 사용합니다.

특정 뷰에서 인스턴스가 해제될 때 subscription들을 함께 해제하고 싶은 경우 사용할 수 있어요.

var cancellable = Set<AnyCancellable>()

let subject1 = PassthroughSubject<Int, Never>()
let subject2 = PassthroughSubject<Int, Never>()

subject1.sink {
    print("subject1 is \\($0)")
}
.store(in: &cancellable)

subject2.sink {
    print("subject2 is \\($0)")
}
.store(in: &cancellable)

subject1.send(1)
subject2.send(1)

print(cancellable)
cancellable.removeAll()
subject1.send(2) // x
subject2.send(2) // x
print(cancellable)

// subject1 is 1
// subject2 is 1
// [Combine.AnyCancellable, Combine.AnyCancellable]
// []

 


참고

[iOS - SwiftUI] Combine의 Cancellable (AnyCancellable) 사용 방법

728x90

'Swift' 카테고리의 다른 글

Swift: Dictionary  (0) 2023.12.12
Swift: Combine(4) - 실전압축콤바인예제  (0) 2023.11.03
Swift: Combine(2) - Publisher, Subscriber  (0) 2023.11.03
Swift: Combine(1) - Combine  (0) 2023.11.03
SwiftUI: ViewBuilder  (1) 2023.10.18