[combine] 2. combine 의 삼대장 - Subscriber

miori·2022년 9월 27일
0

ios-combine

목록 보기
3/5
post-thumbnail

애플의 firstparty framework : combine 정복

이번글은 combine의 삼대장인 Publisher, Subscriber, Operator 중 Subscriber에 대해 정리해보겠다.

Subscriber

정의

A Subscriber instance receives a stream of elements from a Publisher, along with life cycle events describing changes to their relationship.

즉, Subscriber는 Publisher로 부터 elements stream을 받는다.

subscriber의 definition을 보면 다음과 같다.

@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
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: 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>)
}

위의 구현을 통해, 알수 있는 점은 Publihser가 주는 값을 받기 때문에, <Input, Failure> 타입이 일치해야한다는 점이다.

Convenience Subscribers

Apple 에서 쉽게 Subscribers를 사용할 수 있게 Subscribers protocol을 준수하는 class 를 미리 구현해놓았다.
종류로는 Sink, Assign 이 있다.

- Sink

A simple subscriber that requests an unlimited number of values upon subscription.

sink의 경우 Publisher가 제공한 값을 받을수 있는 클로저를 제공한다.

코드로 보면 이해가 쉽다.

let arrPublisher = [1,3,5,7,9].publisher
let subscription2 = arrPublisher.sink { value in
    print("received value: \(value)")
}

출력은 아래와 같다.

received value: 1
received value: 3
received value: 5
received value: 7
received value: 9

이런식으로 sink를 사용할 경우 클로저로 값을 받을 수 있다.

- Assign

A simple subscriber that assigns received elements to a property indicated by a key path.

assign의 경우, Publisher가 제공한 값을 키패스에 할당할 수 있다.

class AssignClass {
    var property: Int = 0 {
        didSet {
            print("Did set \(property)")
        }
    }
}

let object1 = AssignClass()
let subscription3 = arrPublisher.assign(to: \.property, on: object1)
print("final value : \(object1.property)")

출력은 아래와 같다.

Did set 1
Did set 3
Did set 5
Did set 7
Did set 9
final value : 9

AssignClass에서 property라는 프로퍼티에 didSet을 사용하여, 값이 바뀔때마다 print가 되게끔 작성하였다.
그렇기 때문에 [1,3,5,7,9]의 배열의 원소들을 내보내는 Publihser의 값을 받아 print하는 것을 확인할수 있다.


다음은 삼대장중 마지막 Operator에 대해 정리해보도록 하겠다.

profile
iS를 공부하는 miori 입니다.

0개의 댓글