[iOS] Combine에 대하여

Zoe·2023년 12월 12일
0

iOS

목록 보기
33/39

✅ PassthroughSubject

PassthroughSubject란?
Combine 프레임워크에서 제공하는 Publisher의 한 종류
외부에서 값을 받아 구독자들에게 전달하는 역할
PassthroughSubject는 초기값을 가지지 않으며, 오직 새로운 값이 입력될 때만 전달한다.


let subject = PassthroughSubject<Int, Never>()

subject.sink { value in
    print("Received value: \(value)")
}.store(in: &cancellables)

subject.send(1)
subject.send(2)

✅ @Published

@Published란?
해당 프로퍼티의 값이 변경될 때마다 구독자에게 알림을 보낸다.
주로 데이터 바인딩과 상태 관리에 사용

class ViewModel: ObservableObject {
    @Published var score = 0
}

let model = ViewModel()
model.$score.sink { newScore in
    print("New score: \(newScore)")
}.store(in: &cancellables)

model.score = 10

✅ AnyCancellable

AnyCancellable란 ?
구독을 취소할 수 있는 객체를 나타낸다.
Combine에서는 구독을 관리하고 메모리 누수를 방지하기 위해 구독 결과를 AnyCancellable 타입의 인스턴스에 저장한다.

var cancellables = Set<AnyCancellable>()

let publisher = Just("hello!")
publisher.sink { value in
    print(value)
}.store(in: &cancellables)

✅ sink

sink 란?
Publisher에 구독을 생성하고, 발행된 값을 받을 수 있는 클로저를 제공한다.
sink를 사용하면 구독자는 Publisher가 방출하는 값을 받아 처리할 수 있습니다.

let publisher = Just("hello!")
publisher.sink { value in
    print(value)
}.store(in: &cancellables)
profile
iOS 개발자😺

0개의 댓글

관련 채용 정보