Publishers.Last

μ œλ„€λ¦­ ꡬ쑰체 | 슀트림이 μ’…λ£Œν•œ ν›„ 슀트림의 λ§ˆμ§€λ§‰ μš”μ†Œλ§Œμ„ λ°œν–‰ν•˜λŠ” Publisher

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

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

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

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

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

// Combine Last : 5
// Combine Last Finish

μƒμœ„ PublisherλŠ” 1, 2, 3, 4, 5의 값을 μ°¨λ‘€λŒ€λ‘œ λ‚Έλ‹€.

last에 μ˜ν•΄ λ§ˆμ§€λ§‰ μš”μ†Œλ§Œ λ°œν–‰λ˜λ©°, 결과적으둜 5의 값을 λ‚΄κ³  μ’…λ£Œν•œλ‹€.

RxSwift

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

Observable.from([1, 2, 3, 4, 5])
  .takeLast(1)
  .subscribe(onNext: { value in
    print("RxSwift Last : \(value)")
  }, onError: { _ in
    print("RxSwift Last Error")
  }, onCompleted: {
    print("RxSwift Last Finish")
  })
  .disposed(by: disposeBag)

// RxSwift Last : 5
// RxSwift Last Finish

ReactiveSwift

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

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

// ReactiveSwift Last : 1
// ReactiveSwift Last Finish

μ°Έκ³ 

ReactiveX - Operators - Last

Last updated