Publishers.First

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

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

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

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

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

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

// Combine First : 1
// Combine First Finish

์ƒ์œ„ Publisher๋Š” 1, 2, 3, 4, 5์˜ ๊ฐ’์„ ์ฐจ๋ก€๋Œ€๋กœ ๋‚ธ๋‹ค.

first์— ์˜ํ•ด ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋งŒ ๋ฐœํ–‰๋˜๋ฉฐ, ๊ฒฐ๊ณผ์ ์œผ๋กœ 1์˜ ๊ฐ’์„ ๋‚ด๊ณ  ์ข…๋ฃŒํ•œ๋‹ค.

RxSwift

first ์˜คํผ๋ ˆ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

Observable.from([1, 2, 3, 4, 5])
  .first()
  .subscribe(onSuccess: { value in
    print("RxSwift First : \(value)")
  }, onError: { _ in
    print("RxSwift First Error")
  })
  .disposed(by: disposeBag)

// RxSwift First : Optional(1)

ReactiveSwift

first ์˜คํผ๋ ˆ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

SignalProducer([1, 2, 3])
  .first()?.signal
  .observe { event in
    switch event {
    case let .value(value):
      print("ReactiveSwift First : \(value)")
    case .failed:
      print("ReactiveSwift First Error")
    case .completed:
      print("ReactiveSwift First Finish")
    default:
      break
    }
  }

// ReactiveSwift First : 1
// ReactiveSwift First Finish

์ฐธ๊ณ 

ReactiveX - Operators - First

Last updated

Was this helpful?