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

Was this helpful?