본문 바로가기

iOS/Combine

CombineLatest

Subscribes to an additional publisher and publishes a tuple upon receiving output from either publisher.

 

  • 추가의 퍼블리셔 를 연결하여 Tuple 형태로 묶어서 값을 방출하는 연산자
var cancellables: Set<AnyCancellable> = []

let left = PassthroughSubject<String, Never>()
let right = PassthroughSubject<String, Never>()

let combineLatest = Publishers.CombineLatest(left, right)

combineLatest.sink(receiveValue: { result in
    print("combineLatest: \\(result.0), \\(result.1)")
})
.store(in: &cancellables)

left.send("Left")
right.send("Right")
right.send("Right2")
left.send("Left2")

// 결과값

combineLatest: Left, Right
combineLatest: Left, Right2
combineLatest: Left2, Right2
  • 두 퍼블리셔에 모두 값이 들어와야 동작하며, 구독을 시작한 이후로는 두 퍼블리셔 중 하나의 값만 최신 값으로 업데이트 되어도 값을 방출한다.

예제코드

https://github.com/davidyoon891122/CombineProject

참고

https://reactivex.io/documentation/operators/combinelatest.html

'iOS > Combine' 카테고리의 다른 글

Zip  (0) 2024.04.23
WithLatestFrom  (0) 2024.04.22