为了账号安全,请及时绑定邮箱和手机立即绑定

定期订阅来自 Retrofit 的 Observable

定期订阅来自 Retrofit 的 Observable

qq_笑_17 2023-07-28 16:21:55
我正在尝试使用 Retrofit 运行 REST api 调用并让它返回并可观察,但目前我只能弄清楚如何将其设置为延迟,但不幸的是跳过了“第一个间隔”在这里我试图获取联系人列表public interface IContactWebApi {    @GET ("api/GetContactsByGroup")    Observable<Groups> getContactsByGroupSync(@Query ("id") String deviceUid);}这是我使用延迟获得可观察值的地方public void syncContacts(String address, String uid, int interval) {   Retrofit retrofit = getRetrofit(address, true);    Observable<List<Group>> groupObservable = retrofit.create(IContactWebApi.class)            .getContactsByGroupSync(id)            .subscribeOn(Schedulers.io())            .delay(interval, TimeUnit.SECONDS)            .onErrorResumeNext(Observable.empty())            .repeat()            .observeOn(AndroidSchedulers.mainThread());        groupObservable.subscribe(groups -> handleGroups(groups));}我看到了一些建议 Observable.interval 的建议,但我似乎不知道如何将其与另一个间隔一起使用。到目前为止,我能做的最好的事情就是无延迟地运行一次,然后在 subscribe lamda 中,我将可观察值替换为有延迟的可观察值    Observable<List<Group>> groupObservable = retrofit.create(IContactWebApi.class)            .getContactsByGroupSync(uid)            .map(Groups::getGroups)            .subscribeOn(Schedulers.io())            .onErrorResumeNext(Observable.empty())            .observeOn(AndroidSchedulers.mainThread());    groupObservable.subscribe(groups -> {        handleGroups(groups)        retrofit.create(IContactWebApi.class)                .getContactsByGroupSync(uid)                .map(Groups::getGroups)                .subscribeOn(Schedulers.io())                .delay(interval, TimeUnit.SECONDS)                .onErrorResumeNext(Observable.empty())                .repeat()                .observeOn(AndroidSchedulers.mainThread())                .subscribe(groups2 -> handleGroups(groups2));    });有谁知道更好的方法来做到这一点?
查看完整描述

1 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

看来你可以只interval使用flatMap

IContactWebApi api = retrofit.create(IContactWebApi.class);
Observable.interval(interval, TimeUnit.SECONDS)
        .flatMap(i -> api.getContactsByGroupSync(uid))
        .map(Groups::getGroups)
        .subscribeOn(Schedulers.io())
        .onErrorResumeNext(Observable.empty())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(groups -> handleGroups(groups));


查看完整回答
反对 回复 2023-07-28
  • 1 回答
  • 0 关注
  • 81 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信