ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • RxSwift - amb(_:), switchLatest()에 대해서 알아보자
    Ray Wenderlich/RxSwift 2020. 2. 10. 22:02



    Ch9. Combining operatiors p.191 - p.193

    RxSwift에는 "Switching" 오퍼레이터라고 불리는 2개의 주요 오퍼레이터가 있다.

    바로 amb(_:)와 switchLatest()다.


    이 오퍼레이터들은 컴바인한 이벤트 또는 여러 시퀀스들 중에서 하나의 시퀀스로 Switch해준다.

    (원문: They both allow you to produce an observable sequence by switching between the events of the combined or source sequences.)

    이를 통해 우리는 런타임에 어떤 시퀀스를 사용할 지 결정할 수 있게 된다.


    amb(_:)

    amb는 ambiguous의 약자다.


    let left = PublishSubject<String>()

    let right = PublishSubject <String>() 


    // 1

    let observable = left.amb(right)

    let disposable = observable.subscribe(onNext: { value in 

    print(value)

    }) 


    // 2 

    left.onNext("Lisbon"

    right.onNext("Copenhagen"

    left.onNext("London"

    left.onNext("Madrid"

    right.onNext("Vienna"


    disposable.dispose()


    1. left, right 둘 사이에서 애매~한 상황의 시퀀스를 생성했다.

    2. left를 시작으로 next이벤트가 발생한다.


    Lisbon

    London

    Madrid


    amb(_:)는 amb(_:)로 엮인 여러 시퀀스 중에서 가장 먼저 이벤트를 발생시킨 시퀀스의 이벤트만 전달받는다.

    예시에서는 left시퀀스가 가장 먼저 이벤트를 발생시켰으므로, right시퀀스에서 발생하는 이벤트는 전달되지 않는다. (선착순ㅋㅋ)


    오퍼레이터의 이름 ambiguous와 참 잘어울린다.


    '많은 서버 연결 시도 중, 가장 먼저 응답을 준 서버와 통신을 계속한다' 

    이런 시나리오에 적합한 오퍼레이터라고 볼 수 있다.


    이보다 좀 더 많이 사용하는 switchLatest()에 대해서 알아보자.

    switchLatest()


    // 1

    let one = PublishSubject<String>() 

    let two = PublishSubject<String>() 

    let three = PublishSubject<String>() 

    let source = PublishSubject<Observable<String>>()


    // 2 

    let observable = source.switchLatest() 

    let disposable = observable.subscribe(onNext: { value in 

    print(value) 

    })


    // 3 

    source.onNext(one

    one.onNext("Some text from sequence one"

    two.onNext("Some text from sequence two"


    source.onNext(two

    two.onNext("More text from sequence two"

    one.onNext("and also from sequence one"


    source.onNext(three

    two.onNext("Why don't you see me?"

    one.onNext("I'm alone, help me"

    three.onNext("Hey it's three. I win."


    source.onNext(one

    one.onNext("Nope. It's me, one!")


    disposable.dispose()

    1. 3개의 시퀀스를 만들고, 이 시퀀스들을 Element로 가지는 시퀀스를 하나 생성했다. (뭔가 flatMap에서 보던느낌. ㅇㅈ? 제발..)

    2. switchLatest()로 시퀀스를 개조했음.

    3. source에 one이벤트가 전달되었다. 그 다음, one.onNexttwo.onNext로 이벤트가 전달되는데 two에서 발생한 이벤트는 무시된다. 아래로 쭈욱 마찬가지



    --- Example of: switchLatest --- 

    Some text from sequence 

    one More text from sequence two 

    Hey it's three. I win. 

    Nope. It's me, one!



    flatMapLatest와 동작이 유사하다. (https://rhammer.tistory.com/303)

    실제로 flatMapLatest가 flatMap + switchLatest라고 위 포스트에서 언급하였다.



Designed by Tistory.