Publishers.PrefixWhile

μ œλ„€λ¦­ ꡬ쑰체 | 주어진 쑰건 ν΄λ‘œμ €κ°€ μš”μ†Œλ₯Ό λ°œν–‰ν•˜λŠ” 것을 계속해야 ν•˜λŠ”μ§€ λ‚˜νƒ€λ‚΄λŠ” λ™μ•ˆ μš”μ†Œλ₯Ό λ‹€μ‹œ λ°œν–‰ν•˜λŠ” Publisher

주어진 쑰건을 ν†΅κ³Όν•˜λŠ” λ™μ•ˆ ν•΄λ‹Ή μš”μ†Œλ₯Ό λ‹€μ‹œ λ°œν–‰ν•˜λ©°, 주어진 쑰건을 ν†΅κ³Όν•˜μ§€ λͺ»ν•˜λ©΄ μ’…λ£Œν•œλ‹€.

μ΄λ‹ˆμ…œλΌμ΄μ €λŠ” 두 개의 인자λ₯Ό λ°›λŠ”λ‹€.

  • upstream : μƒμœ„μ— 흐λ₯΄λŠ” Publisher

  • predicate : μš”μ†Œ λ°œν–‰μ„ 계속해야 ν•˜λŠ”μ§€ κ²°μ •ν•˜λŠ” ν΄λ‘œμ €

prefix μ˜€νΌλ ˆμ΄ν„°μ™€ 관련이 μžˆλ‹€.

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

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

// Combine PrefixWhile : 1
// Combine PrefixWhile : 2
// Combine PrefixWhile Finish

μƒμœ„ PublisherλŠ” 1, 2, 3의 값을 μ°¨λ‘€λŒ€λ‘œ λ‚΄κ³ , 3 미만인 λ™μ•ˆ 값을 내도둝 ν•˜λŠ” 쑰건을 μ„€μ •ν•˜μ˜€λ‹€.

λ”°λΌμ„œ 1, 2의 값은 쑰건을 ν†΅κ³Όν•˜μ§€λ§Œ 3의 값은 쑰건을 ν†΅κ³Όν•˜μ§€ λͺ»ν•œλ‹€.

결과적으둜 1, 2의 값을 λ‚΄κ³  μ’…λ£Œν•œλ‹€.

RxSwift

takeWhile μ˜€νΌλ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•˜μ—¬ κ΅¬ν˜„ν•  수 μžˆλ‹€.

Observable.from([1, 2, 3])
  .takeWhile { $0 < 3 }
  .subscribe(onNext: { value in
    print("RxSwift PrefixWhile : \(value)")
  }, onError: { _ in
    print("RxSwift PrefixWhile Error")
  }, onCompleted: {
    print("RxSwift PrefixWhile Finish")
  })
  .disposed(by: disposeBag)

// RxSwift PrefixWhile : 1
// RxSwift PrefixWhile : 2
// RxSwift PrefixWhile Finish

ReactiveSwift

take μ˜€νΌλ ˆμ΄ν„°λ₯Ό μ‚¬μš©ν•˜μ—¬ κ΅¬ν˜„ν•  수 μžˆλ‹€.

SignalProducer([1, 2, 3])
  .take { $0 < 3 }
  .start { event in
    switch event {
    case let .value(value):
      print("ReactiveSwift PrefixWhile : \(value)")
    case .failed:
      print("ReactiveSwift PrefixWhile Error")
    case .completed:
      print("ReactiveSwift PrefixWhile Finish")
    default:
      break
    }
  }

// ReactiveSwift PrefixWhile : 1
// ReactiveSwift PrefixWhile : 2
// ReactiveSwift PrefixWhile Finish

μ°Έκ³ 

ReactiveX - Operators - Take

Last updated