Search code examples
swiftoperatorsrx-javalong-pollingrx-swift

Long Polling with RxSwift


I want to make a simple long polling request with RxSwift which may be the similar to RxJava code below:

api.loadHotels(searchRequest)
    .repeatWhen(obs -> observable.delay(3, TimeUnit.SECONDS))
    .takeUntil(searchResponse -> searchResponse.isCompleted)
    .subscribe(listener::hotelListLoaded);

In RxSwift, there is a repeatWhen operator that takes an ObservableConvertibleType as a parameter, not passing the chained Observable to its closure as an argument, unlike its synonym in RxJava.

What I expected in RxSwift: api.loadHotels(searchRequest).repeatWhen{result -> ObservableConvertibleType} so I can write the exact same logic as RxJava code. But I cannot achieve this. Because it is only as api.loadHotels(searchRequest).repeatWhen(ObservableConvertibleType) The exact same thing applies for RxSwift's takeUntil operator.

However I also tried: repeatWhen operator in RxSwift and repeatWhen substituter in RxSwift

So my question is: how can I achieve the same logic in RxSwift as the given RxJava code? Am I getting the workflow of current repeatWhen and takeUntil operators of RxSwift wrong?


Solution

  • How about something like this?:

    let hotelRequest = api.loadHotels(searchRequest)
    
    hotelRequest.repeatWhen {
        return hotelRequest.flatMapLatest { result in
            // now you have your chance to use `result -> ObservableConvertibleType`
        }
    }