[combine] 3. combine 의 삼대장 - Operator

miori·2022년 10월 1일
0

ios-combine

목록 보기
4/5
post-thumbnail

애플의 firstparty framework : combine 정복

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

Operator

Operator 역할

Operator는 Publisher 에게 받은 값을 가공해서 Subscriber 에게 전달한다.
이는 곧 combine의 장점이 된다.
애플 공식문서에 다음과 같이 적혀있다.

The advantage of Combine comes from combining operators to customize event delivery.

공식문서처럼 Combine의 Operator를 사용하여 받은 값을 원하는 형태로 가공하여, Subscriber에게 전달해 줄 수 있다.

Operator 예시

swift는 함수를 First Class Citizen(일급 객체)으로 취급하기 때문에 함수를 다른 함수의 파라미터로 사용할 수 있다.
이렇게 매개변수로 함수를 갖는 함수를 고차함수라 하고, 고차함수에는 map, filter, reduce등이 있다.
swift를 사용해 프로그래밍 하다보면, map, filter를 사용하여 데이터 연산을 자주 했었다.

이처럼 combine에서도 map(_:), flatMap(maxPublishers:_:), reduce(_:) 같은 operator를 제공하고 이는 위에서 말한 swift 표준 라이브러리에 있는 operator와 유사하게 동작한다.

- map

let intPublisher = PassthroughSubject<String, Never>()
let subscription1 = intPublisher
    .map { "hello " + $0 }
    .sink { value in
        print("operator map result: \(value)")
    }

intPublisher.send("miori")
subscription1.cancel()

코드로 예시를 보면 다음과 같다.
실행 결과 operator map result: hello miori 다음과 같이 출력이 된다.

map을 사용하면 Publihser가 보낸 값을 가공하여, Subscriber에게 전달을 한다.

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

0개의 댓글