Swift - Combine

최조니·2022년 7월 25일
0

Swift

목록 보기
6/10

Combine

  • 이벤트 처리 연산자들을 통해 비동기 이벤트들을 핸들링 할 수 있게 해줌

  • publishers
    시간에 따른 값을 제공

  • subscribers
    publishers로부터 해당 값을 받음


publishers

  • 시간에 따른 값의 흐름을 전달할 수 있는 프로토콜

  • 값을 받아 처리하고 다시 전달하는 연산자들

  • OutputFailure

    • 에러가 발생했을 경우 Failure, 그렇지 않으면 Output 전달
  • Publisher 중 ConnectablePublisher 프로포콜을 준수하는 Publisher는 autoconnext를 이용하여 subscriber 연결 여부와 상관 없이 미리 데이터를 발행시킬 수 있음


subscribers

  • 값을 수신받을 때 동작

  • InputFailure

    • 이때의 Input 은 publisher의 Output과 타입이 같음
    • Failure 또한 publisher의 Failure과 타입이 같음

예제

Just · sink

Just(5).sink {
	print($0)
}    
  • Just : 오직 하나의 값만 출력하고 끝나는 단순한 Publisher

    • Output 타입 : 인자로 받는 값의 타입
    • Failure 타입 : Never
  • sink : 클로저 형태로 데이터를 받는 Subscriber

    • Input 타입 : 클로저로 받게되는 데이터 값
    • Failure 타입 : Never

간단 예제 1)

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
완료

간단 예제 2)

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

참고 사이트

profile
Hello zoni-World ! (◍ᐡ₃ᐡ◍)

0개의 댓글