gpt4 book ai didi

android - 定期轮询后端 API 一定次数 - Retrofit & RxJava

转载 作者:太空狗 更新时间:2023-10-29 16:11:52 24 4
gpt4 key购买 nike

我希望以预定义的固定时间间隔轮询后端调用一定次数。如果我在循环之间收到预期的有效负载,我想退出循环并更新 UI,否则终止轮询。

下面是我在进行标准 http 调用时通常执行的代码。

//Response Model from backend API
public class ApplicationStatusResponse
{
public boolean isActive;
}

//Retrofit facade
@POST(v1/api/applicationStatus)
Single<ApplicationStatusResponse> checkApplicationStatus(@Body ApplicationStatusRequest applicationRequest);


-----

DisposableSingleObserver<ApplicationStatusResponse> disposableSingleObserver = new DisposableSingleObserver<ApplicationStatusResponse>() {
@Override
public void onSuccess(ApplicationStatusResponse response) {
// Update UI Here
}

@Override
public void onError(Throwable e) {

}
};

CompositeDisposable compositeDisposable = new CompositeDisposable();

// Following call works alaways works
DisposableSingleObserver<ApplicationStatusResponse> disposable = originationRepo.checkApplicationStatus(applicationStatusRequest)
.observeOn(schedulerProvider.mainThread())
.subscribeWith(disposableSingleObserver);

compositeDisposable.add(disposable);

但是我有点迷失在下面的代码中,语法错误,当从 Flowable.interval 调用时我无法使用相同的 disposableSingleObserver 并且在我需要更新 UI 的用例中需要帮助定期状态,直到时间过去或状态处于 Activity 状态,以先发生者为准,而且如果我收到 HTTP 状态代码 500,我也不会在终止轮询后重复,直到满足上述条件。

 //Help Needed here  when I need polling in regular interval - I am kind of the syntax error complain from Android Studio

int INITIAL_DELAY = 0;
int POLLING_INTERVAL = 1000;
int POLL_COUNT = 8;

disposable = Flowable
.interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
.map(x -> originationRepo.checkApplicationStatus(applicationStatusRequest))
.take(POLL_COUNT) ??
// How can I receive the response payload and update the UI

compositeDisposable.add(disposable);

提前感谢您的帮助。

最佳答案

(继续 MyDogTom's answer,您还可以通过抛出自定义错误/异常来“短路”可观察对象)

选项 3:

disposable = Flowable
.interval(INITIAL_DELAY, POLLING_INTERVAL, TimeUnit.MILLISECONDS)
.map(x -> originationRepo.checkApplicationStatus(applicationStatusRequest)) // .flatMap (?)
.take(POLL_COUNT) //YES
.doOnNext() // update UI here
.map(response -> {
if(!response.checkCondition()) {
throw new ShortCircuitException();
}
return response.data();
})
.onErrorResumeNext(throwable -> (throwable instanceof ShortCircuitException)
? Observable.empty()
: Observable.error(throwable))

关于android - 定期轮询后端 API 一定次数 - Retrofit & RxJava,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44920829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com