ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Combine Cancellable, subscription
    IOS/Combine 2024. 4. 7. 10:38

    Cancellable protocol

    애플에선 Cancellable 프로토콜을 activitiy or action들을 cancellation 할 수 있게 도와주는 프로토콜이라 설명하고 있습니다.

    이런 Cancellable protocol을 conforming 하는 타입은 Combine에서 .sink, assign을 통한 구독자 생성 메소드가 있습니다.

    A protocol indicating that an activity or action supports cancellation.

    subscription

    Apple Doucment 참조/ Cancellable을 상속

     

    Subscriber와 Publisher 사이를 이어주는 역할을 하는 프로토콜이자 Combine의 중요 개념입니다.

    Combine에선, Subscriber - Publisher 사이 스트림을 이어주는 역할을 subscription에서 하며, 방출 된 값을 Subscriber에게 전달하는 통로 역할로 subscription이 사용되는 메커니즘을 가지고 있습니다.

     

    이런 subscipriont은 시간에 따른 스트림에서 정의되고 독립적인 존재이기 때문에, 한 번만 cancel이 발생하게 됩니다. 즉, 취소되고 Deallocated 된 걸 다시 살릴 수가 없다는 얘기가 되겠죠.

    Cancellable Token이란?

    Combine에선 구독을 시작하면 Cancellable 인스턴스를 return값으로 반환하며 이를 Cancellable Token이라 합니다.

    이러한 Cancellable Token으로 해당 subscription을 취소할 수 있는 메커니즘을 제공됩니다.

     

    AnyCancellable

    이런 Cancellable Object들을 type-erasing해서 관리하며 자동으로 메모리가 해제될 때 관리하고 있는 Cancellable들을 모두 구독을 취소함으로써 간단하게 관리할 수 있는 클래스입니다.

     

    예제코드

    var subscriptions = Set<AnyCancellable>()
    
    [1,2,3].publisher
    	// sink를 통한 구독시 Cancellable Token 반환
        .sink { 
            print($0)
        } 
        // 이런 Cancellable Token들을 .store를 통해 저장
        .store(in: &subscriptions)

     

    'IOS > Combine' 카테고리의 다른 글

    Combine Operators 2(Replace)  (1) 2024.04.21
    Combine Operators 1 (transforming)  (0) 2024.04.13
    Combine - Subscriber 2편  (0) 2024.03.30
    Combine - Subscriber 1편  (0) 2024.03.16
    Combine 구성요소 Publisher  (0) 2024.03.10
Designed by Tistory.