RxSwift 정리 5 - operators(.withLatestFrom .sample .amb .switchLatest .retry(when:))

2021. 8. 23. 17:08Developer.TokkiSea/Apple

반응형

 

.withLatestFrom() .sample()

.withLatestFrom : 가장 최근 발생값을 계속 subscribe한다.

.sample : 가장 최근 발생값을 subscribe한다.

이후 새로운 값이 없다면 발생값이 없다.

sample = withLatestFrom + distinctUntilChanged() 와 같다.

let button = PublishSubject<Void>()
let textField = PublishSubject<String>()
button.withLatestFrom(textField)
// textField.sample(button) 
	.subscribe(onNext: { value in
    	print(value)
})
textField.onNext("Typ")
textField.onNext("Typin")
textField.onNext("Typing...")
button.onNext(()) // withLatestFrom : Typing...  , sample : Typing...
button.onNext(()) // withLatestFrom : Typing...  , sample :
textField.onNext("Typed...")
button.onNext(()) // withLatestFrom : Typed...  , sample : Typed...
button.onNext(()) // withLatestFrom : Typed...  , sample :

 

.amb()

left.amb(right) 에서 left, right 상관없이 먼저 발생한 요소를

계속해서 subscribe 한다.

let left = PublishSubject<String>()
let right = PublishSubject <String>() 
let observable = left.amb(right)
let disposable = observable.subscribe(onNext: { value in 
	print(value)
}) 
right.onNext("r1") 
left.onNext("l1") 
left.onNext("l2") 
left.onNext("l3") 
right.onNext("r2")
disposable.dispose()
// r1, r2

 

 

.switchLatest()

.flatMapLatest() 와 비슷하다.

다만 스위치용도의 시퀸스로 사용할 시퀸스를 선택한다.

let one = PublishSubject<String>()
let two = PublishSubject<String>()
let three = PublishSubject<String>()
let source = PublishSubject<Observable<String>>()
let observable = source.switchLatest()
let disposable = observable.subscribe(onNext: { value in
    print(value)
})
source.onNext(one) // switched one
one.onNext("one 1") // one 1
two.onNext("two 1") //
source.onNext(two) // switched two
two.onNext("two 2") // two 2
one.onNext("one 2") //
source.onNext(three) // switched three
two.onNext("two 3") //
one.onNext("one 3") //
three.onNext("three 1") // three 1
source.onNext(one) // switched one
one1.onNext("one 4") // one 4

 

.retry(when:)

네트워크 에러에 대해 

let retryHandler: (Observable<Error>) -> Observable<Int> = { error in
  error.flatMap { e in
      return (e as NSError).code > 900 
      ? Observable.error(e) 
      : Observable<Int>.timer(RxTimeInterval.milliseconds(1000), scheduler: MainScheduler.instance).take(1) 
  }
}

observable.retry(when:retryHandler).subscribe(....)

 

 

 

 

 

 

 

 

 

.withLatestFrom .sample .amb .switchLatest .retry(when:))

반응형