이벤트 처리 연산자들을 통해 비동기 이벤트들을 핸들링 할 수 있게 해줌
publishers
시간에 따른 값을 제공
subscribers
publishers
로부터 해당 값을 받음
시간에 따른 값의 흐름을 전달할 수 있는 프로토콜
값을 받아 처리하고 다시 전달하는 연산자들
Output
과 Failure
Failure
, 그렇지 않으면 Output
전달Publisher 중 ConnectablePublisher 프로포콜을 준수하는 Publisher는 autoconnext를 이용하여 subscriber 연결 여부와 상관 없이 미리 데이터를 발행시킬 수 있음
값을 수신받을 때 동작
Input
과 Failure
Input
은 publisher의 Output
과 타입이 같음Failure
또한 publisher의 Failure
과 타입이 같음Just(5).sink {
print($0)
}
Just
: 오직 하나의 값만 출력하고 끝나는 단순한 Publisher
Never
sink
: 클로저 형태로 데이터를 받는 Subscriber
Never
import Combine
var myIntArrayPublisher:Publishers.Sequence<[Int], Never> = [1,2,3].publisher
myIntArrayPublisher.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("완료")
case .failure(let error):
print("실패 : error \(error)")
}
}, receiveValue: { receviedValue in
print("값을 받았다. \(receviedValue)")
})
→ 결과 화면
값을 받았다. 1
값을 받았다. 2
값을 받았다. 3
완료
import Combine
var mySubscription: AnyCancellable?
var myNotification = Notification.Name("com.swm.customNotification")
var myDefaultPublisher = NotificationCenter.default.publisher(for: myNotification)
mySubscription = myDefaultPublisher.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("완료")
case .failure(let error):
print("실패 error: \(error)")
}
}, receiveValue: { receivedValue in
print("받은 값 : \(receivedValue)")
})
NotificationCenter.default.post(Notification(name: myNotification))
NotificationCenter.default.post(Notification(name: myNotification))
NotificationCenter.default.post(Notification(name: myNotification))
→ 결과 화면
받은 값 : name = com.swm.customNotification, object = nil, userInfo = nil
받은 값 : name = com.swm.customNotification, object = nil, userInfo = nil
받은 값 : name = com.swm.customNotification, object = nil, userInfo = nil