【问题标题】:Subscribe to Observable from Retrofit Periodically定期订阅 Observable from Retrofit
【发布时间】:2020-01-14 18:14:30
【问题描述】:

我正在尝试使用 Retrofit 运行 REST api 调用并让它返回和 Observable 但目前我只能弄清楚如何将其设置为延迟,但不幸的是跳过了“第一个间隔”

我在这里尝试获取联系人列表

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 的建议,但我似乎无法弄清楚如何将它与另一个间隔一起使用。到目前为止,我设法做的最好的事情是立即运行一次,然后在订阅 lamda 中,我将 observable 替换为一个延迟

    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));
    });

有人知道更好的方法吗?

【问题讨论】:

    标签: java retrofit rx-java


    【解决方案1】:

    看来你可以只用intervalflatMap

    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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 2023-04-02
      • 2018-08-28
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多