티스토리 뷰

동기와 비동기 처리를 공부했으니 이젠 컴바인을 알아보도록하자

컴바인(Combine)

The Combine framework provides a declarative Swift API for processing values over time.
Combine 프레임워크는 시간에 따른 값을 처리하기 위한 선언적 Swift API를 제공합니다

These values can represent many kinds of asynchronous events.
이러한 값은 여러 종류의 비동기 이벤트를 나타낼 수 있습니다.

Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers.
Combine은 시간에 따라 변경될 수 있는 값을 노출하도록 publishers 를 선언하고 , subscribers 는 publishers 로부터 해당 값을 수신하도록 선언합니다.

  • publishers : 값이 변경되면 값을 내보내는 구나
  • subscribers : publishers가 보내는 값을 받을 수 있구나

그래서 왜 쓰는가!?

you’ll make your code easier to read and maintain, by centralizing your event-processing code and eliminating troublesome techniques like nested closures and convention-based callbacks.
번거로운 중첩된 클로저 제거! 규칙기반 콜백 제거! 중앙화된 이벤트 처리 코드!, 읽기 쉬운 코드!, 쉬운 유지 관리!

주요 개념

Publisher

Declares that a type can transmit a sequence of values over time
시간이 지남에 따라 일련의 값을 전송할 수 있는 유형을 선언

  • Just : 가장 단순한 형태, 에러타입: Never
  • Promise : Just와 비슷하지만 Filter Type을 정의 할 수 있음
  • Fail : 정의된 실패타입을 내보냄
  • Empty : 어떤 데이터도 발행하지 않는 퍼블리셔, 에러처리나 옵셔널 값을 처리할 때 사용
  • Sequence : 데이터를 순차적으로 발행하는 퍼블리셔, (1...10).Publisher
  • ObservableObjectPublisher : SwiftUI에서 사용되는 ObservableObject를 준수하는 퍼블리셔

Subscriber

A protocol that declares a type that can receive input from a publisher.
게시자로부터 입력을 받을 수 있는 유형을 선언

sink : 횟수의 제한 없이 Subscription을 통해 값을 요청하는 간단한 Subscriber

  • 보통 2번 소스로 설명을 들어왔는데 1번의 원형을 보니까 왜 publisher고 subscriber 인지 알것 같다.
let intArrayPublisher = [1,2,3,4,5].publisher

// 1. sink의 원형
let sink = Subscribers.Sink<Int, Never>(
	receiveCompletion: { print("completion: \($0)") },
	receiveValue: { print("value: \($0)") }
)
intArrayPublisher.subscribe(sink)

// 2. 위와 아래는 같은 코드 (https://icksw.tistory.com/275)
intArrayPublisher.sink(
	receiveCompletion: { print("completion: \($0)") },
	receiveValue: { print("value: \($0)")}
)

assign : key path로 표시된 프로퍼티에 수신된 값을 할당하는 간단한 Subscriber (어떤 값을 받아서 어떤 곳에 저장하는 Subscirber)

class testClass {
	var num: Int {
		didSet { print("Set \(num)") }
	}
	init(num: Int) { self.num = num }
}
let obj = testClass(num: 0)
let publisher = [1,2,3,4,5].publisher
let assign = Subscribers.Assign<testClass, Int>(object: obj, keyPath: \.num)

/*
assign이 종료되면 assign이 가지고 있던 object가 deinit되어 소멸된다.
종료된 이후 object에 접근하면 nil이 들어있다.
반면 obj는 살아있지만 값은 5가 저장되어있다.
*/
publisher.subscribe(assign)
Set 1
Set 2
Set 3
Set 4
Set 5
deinit(assign의 object)

Operator

Methods that create downstream publishers or subscribers to act on the elements they receive.
수신한 요소에 따라 작업을 수행하는 다운스트림 publishers 또는 subscribers를 생성하는 방법

  1. 다른 데이터 타입으로 변형
    • scan, setFailureType, map, flatMap
  2. 조건에 맞는 데이터만 허용
    • compactMap, replaceEmpty, filter, removeDuplicates
  3. 데이터 스트림을 모아서 출력
    • collect, reduce, tryReduce, ignoreOutput
  4. 숫자 시퀀스 값과 관련된 스트림을 제어
    • max, count, min
  5. 데이터 시퀀스를 변형
    • prepend, tryFirstWhere, first, last, drop, prefix Operator 종류가 너무 많다.. 여기 있는것도 전부는 아니니 조금씩조금씩 정리하면서 익히는게 맞다.. 또한 first처럼 일반, try, where 등 내부 파라미터에 따라 다양하게 구성된 경우도 많다.

참고자료

'프로그래밍 > iOS' 카테고리의 다른 글

[Combine-1] 동기(Sync), 비동기(Async)  (0) 2025.03.05
SnapKit, Then 알아보자  (0) 2025.03.04
뷰컨트롤러 생명주기  (1) 2024.07.18
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/01   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함