Publishers.FirstWhere

์ œ๋„ค๋ฆญ ๊ตฌ์กฐ์ฒด | ํŠน์ • ์กฐ๊ฑด ํด๋กœ์ €๋ฅผ ๋งŒ์กฑํ•˜๊ธฐ ์œ„ํ•œ ์ŠคํŠธ๋ฆผ์˜ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋งŒ์„ ๋ฐœํ–‰ํ•˜๋Š” Publisher

์ด๋‹ˆ์…œ๋ผ์ด์ €๋Š” ๋‘ ๊ฐœ์˜ ์ธ์ž๋ฅผ ๋ฐ›๋Š”๋‹ค.

  • upstream : ์ƒ์œ„์— ํ๋ฅด๋Š” Publisher

  • predicate : ์–ด๋–ค ์š”์†Œ๋ฅผ ๋ฐœํ–‰ํ• ์ง€ ๊ฒฐ์ •ํ•˜๋Š” ํด๋กœ์ €

์ƒ์œ„ Publisher๋กœ๋ถ€ํ„ฐ ์กฐ๊ฑด ํด๋กœ์ €์— ๋งŒ์กฑํ•˜๋Š” ์š”์†Œ๋ฅผ ๋จผ์ € ๋ฝ‘์•„๋‚ด๊ณ , ๊ทธ ์ค‘์—์„œ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋งŒ์„ ๋ฐœํ–‰ํ•œ๋‹ค.

first ์˜คํผ๋ ˆ์ดํ„ฐ์™€ ๊ด€๋ จ์ด ์žˆ๋‹ค.

// Publishers.FirstWhere Publisher
Publishers
  .FirstWhere(upstream: Publishers.Sequence<[Int], Never>(sequence: [1, 2, 3, 4, 5])) { $0.isMultiple(of: 2) }
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine FirstWhere Error")
    case .finished:
      print("Combine FirstWhere Finish")
    }
  }, receiveValue: { value in
    print("Combine FirstWhere : \(value)")
  })
  .store(in: &cancellables)

// first Operator
Publishers.Sequence<[Int], Never>(sequence: [1, 2, 3, 4, 5])
  .first { $0.isMultiple(of: 2) }
  .sink(receiveCompletion: { completion in
    switch completion {
    case .failure:
      print("Combine FirstWhere Error")
    case .finished:
      print("Combine FirstWhere Finish")
    }
  }, receiveValue: { value in
    print("Combine FirstWhere : \(value)")
  })
  .store(in: &cancellables)

// Combine FirstWhere : 2
// Combine FirstWhere Finish

์ƒ์œ„ Publisher๋Š” 1, 2, 3, 4, 5์˜ ๊ฐ’์„ ์ฐจ๋ก€๋Œ€๋กœ ๋‚ด๊ณ , 2์˜ ๋ฐฐ์ˆ˜์˜ ์กฐ๊ฑด์„ ์„ค์ •ํ–ˆ๋‹ค.

๊ฐ’๋“ค ์ค‘ 2์˜ ๋ฐฐ์ˆ˜์ธ 2, 4 ์ค‘ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋Š” 2์ด๋ฏ€๋กœ, ์ตœ์ข…์ ์œผ๋กœ 2์˜ ๊ฐ’์„ ๋‚ด๊ณ  ์ข…๋ฃŒํ•œ๋‹ค.

RxSwift

ํ•ด๋‹น ๋™์ž‘์„ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•œ ์˜คํผ๋ ˆ์ดํ„ฐ๋ฅผ ์ œ๊ณตํ•˜์ง€ ์•Š๋Š”๋‹ค.

ReactiveSwift

ํ•ด๋‹น ๋™์ž‘์„ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•œ ์˜คํผ๋ ˆ์ดํ„ฐ๋ฅผ ์ œ๊ณตํ•˜์ง€ ์•Š๋Š”๋‹ค.

Last updated

Was this helpful?