簡體   English   中英

定期訂閱來自翻新的Observable

[英]Subscribe to Observable from Retrofit Periodically

我正在嘗試使用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,但似乎無法弄清楚如何在另一個間隔中使用它。 到目前為止,我設法做到的最好是無延遲運行一次,然后在訂閱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));
    });

有誰知道更好的方法嗎?

看來您可以在flatMap使用interval

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM