常小波 常小波 - 11 days ago 7
iOS Question

why concat never() in rxswift

func signup(_ username: String, password: String) -> Observable<Bool> {
// this is also just a mock
let signupResult = arc4random() % 5 == 0 ? false : true
return Observable.just(signupResult)
.concat(Observable.never())
.throttle(0.4, scheduler: MainScheduler.instance)
.take(1)
}


I see some code in RxSwift, But I could not understand why need to
concat(Observable.never())

Answer

I'm making sense of this myself, so take it with a grain of salt :)

  • Observable.just emits the value once and completes immediately; it takes virtually no time at all;
  • .throttle(0.4, scheduler: MainScheduler.instance) introduces time into the sequence, taking 0.4s+ to determine the value to return, and
  • concat(Observable.never()) makes the input sequence long-running so throttle has something to do in the first place.

Now return Observable.just(signupResult) would suffice to implement that function. What's the rest good for?

The other three operators result in a delay. Since the concatenated Observable is never-ending, throttle will wait at least 0.4 seconds once to determine which value to emit for the first throttled "chunk". take(1) then completes the sequence once the first value is emitted after 0.4s

To me, this seems to be a very laborious way to implement a delayed response :)