ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Combine - Subscriber 1편
    IOS/Combine 2024. 3. 16. 08:59

    이번 글은 Combine의 핵심중에 하나인 Subscriber가 무엇이고 어떻게 Publisher를 구독하는지 알아보겠습니다.

    Subscriber는 총 2번에 나누어서 설명드리겠습니다. 이번글은 간단한 개념과 sink를 사용한 구독을 알아보겠습니다!

    Publisher 포스팅은 다음글을 참고해 주세요!

    2024.03.10 - [IOS/Combine] - Combine 구성요소 Publisher

     

    Combine 구성요소 Publisher

    지난 1편은 Combine의 맛보기를 보았고 이제 본격적으로 Combine의 Publisher , Subscription, Subscriber, Operator부터 시작해 다양한 Operator를 공유하려 합니다. 1편은 요기 링크 걸어둘게요!!! 못 보신분은 보고

    jjunbbang.tistory.com

     

    Subscriber

    Publisher는 시간의 흐름에 따라 값, 관심사를 Subscriber에게 방출하는데요, 이걸 Subscriber 하는 대상에 방출하게 됩니다.

    Publisher가 프로토콜로 추상화되어 있는 걸 코드로 보았는데요, Subscriber도 동일하게 정의되어 있습니다.

     

    Developer document

    Publisher와 동일하게 Generic으로 Input, Failure 쌍으로 정의되어 있습니다. 코드를 자세히 보겠습니다.

     

    ★ 아래 Receive 메소드들의 경우 Publisher, Subscriber, Subscription 간의 상호작용에 사용되는 메소드입니다. 쉽게 설명하기 위한 현재 글에선 맞지 않다 생각해서 추후 포스팅할 Custom Subscriber, Puiblisher, Subscription 주제 때 설명할게요!

    public protocol Subscriber<Input, Failure> : CustomCombineIdentifierConvertible {
    
        /// The kind of values this subscriber receives.
        associatedtype Input
    
        /// The kind of errors this subscriber might receive.
        ///
        /// Use `Never` if this `Subscriber` cannot receive errors.
        associatedtype Failure : Error
    
        /// Tells the subscriber that it has successfully subscribed to the publisher and may request items.
        ///
        /// Use the received ``Subscription`` to request items from the publisher.
        /// - Parameter subscription: A subscription that represents the connection between publisher and subscriber.
        func receive(subscription: any Subscription)
    
        /// Tells the subscriber that the publisher has produced an element.
        ///
        /// - Parameter input: The published element.
        /// - Returns: A `Subscribers.Demand` instance indicating how many more elements the subscriber expects to receive.
        func receive(_ input: Self.Input) -> Subscribers.Demand
    
        /// Tells the subscriber that the publisher has completed publishing, either normally or with an error.
        ///
        /// - Parameter completion: A ``Subscribers/Completion`` case indicating whether publishing completed normally or with an error.
        func receive(completion: Subscribers.Completion<Self.Failure>)
    }

    마찬가지로 Subscriber의 Input값은 Conform 하는 어떤 관심사에 의해 정의되어 사용됩니다. 그럼, Pubsher의 Input타입과 이를 Subscribe 하는 Subscriber의 Input타입은 서로 달라질 수도 있다는 생각을 하실 수 있는데 이는 그렇지 않습니다.

    Publisher를 구독하는 Subscriber는 값을 전달받을 때 Publisher Input 타입과 동일한 값을 받게 됩니다.

     

    Sink(receiveCompletion:receiveValue:)

    클로저 형태로 Publisher를 구독하는 메소드라 정의되어 있는데요. 

    Publisher를 구독할 때 가장 간단하게 사용하는 메소드입니다.

    이를 통해 Publisher를 구독하게 된다면, 이 전체 흐름 (방출 - 구독) 관계를 subscription이라 불리게 됩니다!

    var subscriptions = Set<AnyCancellable>()
    
    let publish = [1, 2, 3].publisher
    let subscription = publish
        .sink (receiveCompletion: {print($0)}, receiveValue: {print($0)})
        .store(in: &subscriptions)

     

    메커니즘을 보면, Publisher가 방출한 값을 sink receiveValue 매개변수 클로저에서 처리하게 됩니다. (print문으로 value출력)

    이후 모든 값이 전달되었다면, receiveCompletion 매개변수에 finished이벤트를 받게 되는데요, Subscribers.Completion 매개변수를 보면 다음과 같습니다.

    일반적으로 Publisher가 종료되면 finsihed가 방출됩니다. 따라서 Completion enum에 finished를 subscriber가 받게 되고 그 외 Falure, 즉 Publisher의 실패 유형(Failure type)에따라 Sink receiveCompletion매개 변수에 값이 전달됩니다.

     

    이번 글은 정말 간단하게만 알아봤습니다. 다음 포스팅때는 다른 구독방법 asign(to:on), asign(to) 메소드를 활용한 구독과 함께, 왜 위 예제코드에서 .store를 사용했는지 CancellableToken에 대해 설명 하겠습니다!

     

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

    Combine Operators 1 (transforming)  (0) 2024.04.13
    Combine Cancellable, subscription  (0) 2024.04.07
    Combine - Subscriber 2편  (0) 2024.03.30
    Combine 구성요소 Publisher  (0) 2024.03.10
    Combine Framework란?  (0) 2024.03.03
Designed by Tistory.