이재용의 iOS

Subscription Mechanism in Combine

2024년 7월 11일 • ☕️ 1 min read

    Publishers by nature are inert entities. When the subscriber subscribes to a publisher the publisher instantiates the subscription and start works.

    Publisher는 본질적으로 비활성 엔티티입니다. Subscriber가 Publisher에 구독하면 Publisher는 Subscription을 인스턴스화하고 작업을 시작합니다.

    vmmap

    ✅ 구독 순서

    1. The subscriber, subscribes to the publisher.
      subscriber는 publisher에 구독합니다.
    2. The publisher creates the subscription then sends to the Subscriber (calling receive(subscription:)).
      publisher는 subscription을 생성한 다음 Subscriber에게 보냅니다 (receive(subscription:)를 호출)
    3. The subscriber requests values from the subscription by sending it the number of values it wants (calling the subscription’s request(_:) method).
      subscriber는 subscription에서 값을 요청하기 위해 값을 원하는 수만큼 보냅니다 (subscription의 request(:) 메서드를 호출).
    4. The subscription begins the work and starts emitting values. It sends them one by one to the subscriber (calling the subscriber’s receive(_:) method).
      subscription은 작업을 시작하고 값을 방출합니다. 그것은 값을 하나씩 구독자에게 보냅니다 (구독자의 receive(:) 메서드를 호출).
    5. Upon receiving a value, the subscriber returns a new Subscribers.Demand, which adds to the previous demand.
      값을 받으면 구독자는 새로운 Subscribers.Demand를 반환하여 이전 수요에 추가합니다.
    6. The subscription keeps sending values until the number of values sent reaches the total requested number.
      구독은 보낸 값의 수가 요청된 총 수에 도달할 때까지 값을 계속 보냅니다.

    Note that if a subscription sends total values requested from the subscriber it should awaits for the signal before sending more values. This mechanism is inherent in the heart of the Combine framework. This can be bypassed but may result in unpredictable situations. If there is an error or the subscription’s values source completes, the subscription calls the subscriber’s receive(completion:) method.

    주의해야 할 점은 구독이 구독자로부터 요청된 총 값들을 보낸 경우, 더 많은 값을 보내기 전에 신호를 기다려야 한다는 것입니다. 이 메커니즘은 Combine 프레임워크의 핵심에 내재되어 있습니다. 이를 우회할 수는 있지만, 예측할 수 없는 상황을 초래할 수 있습니다. 에러가 발생하거나 구독의 값 소스가 완료되면, 구독은 구독자의 receive(completion:) 메서드를 호출합니다.