Search

직접 값을 발행하기

태그
Combine 카테고리
퍼블리셔
사용용도 요약
세부 카테고리
작성일
2022/07/10
카테고리
Combine

PassThroughSubject

초기값이 없다.
밖에서 값을 발행할 수 있다.
명령형 코드를 Combine 코드로 이어주는 역할
이렇게 발행된 값은 Subject 를 구독한 모든 Subscriber 에게 전달된다.
발행된 값은 현재 값으로 세팅된다.
example(of: "PassthroughSubject") { enum MyError: Error { case test } final class StringSubscriber: Subscriber { typealias Input = String typealias Failure = MyError func receive(subscription: Subscription) { subscription.request(.max(2)) } func receive(_ input: String) -> Subscribers.Demand { print("Received value", input) return input == "World" ? .max(1) : .none } func receive(completion: Subscribers.Completion<MyError>) { print("Received completion", completion) } } // 4 let subscriber = StringSubscriber() }
Swift
복사

CurrentValueSubject

PassThroughSubject 와 대부분의 기능이 동일
초기값 존재 → 구독과 동시에 초기값 발행.
값을 할당하듯이 사용 가능
var subscriptions = Set<AnyCancellable>() let subject = CurrentValueSubject<Int, Never>(0) subject .sink(receiveValue: { print($0) }) .store(in: &subscriptions) subject.value = 3 // 값을 할당하는 것 처럼 사용이 가능하다 subject.value = .finished // 🚨 컴파일에러 !
Swift
복사