简体   繁体   English

如何使用 rxjava/retrofit 正确等待/观察来自服务器的传入数据

[英]How to wait/observe incoming data from server correctly with rxjava/retrofit

I have a problem with downloading data from server, to be more specific I cannot implement a "waiting/observing incoming data" behavior.我在从服务器下载数据时遇到问题,更具体地说,我无法实现“等待/观察传入数据”行为。 I want to fill up my RecyclerView and Spinner with lists come from server, but right know, the methods return null/empty list.我想用来自服务器的列表填充我的RecyclerViewSpinner ,但我知道,这些方法返回空/空列表。 I understand, the problem is that the method finish before the data arrives.我明白,问题是该方法在数据到达之前完成。

I've checked these two questions which are similar, but none of the answers worked for me:我检查了这两个相似的问题,但没有一个答案对我有用:

Waiting for API Calls to complete with RxJava and Retrofit 使用 RxJava 和 Retrofit 等待 API 调用完成

RXJava retrofit waiting having the UI wait for data to be fetched from API RXJava 改造等待 UI 等待从 API 获取数据

My code:我的代码:

API:应用程序接口:

@GET("/api/categories")
Observable<Response<JsonObject>> getCategories();

netWorker:网络工作者:

public List<String> getCat() {
    List<String> incomingDataSet = new ArrayList<>();
    
    compositeDisposable.add(
        apiConnector.getCategories()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(response -> {
                if (response.code() >= 200 && response.code() < 300) {
                    JsonArray incomingArray = response.body().getAsJsonArray("category");
                    
                    for (int i = 0; i < incomingArray.size(); i++) {
                        incomingDataSet.add(incomingArray.get(i).getAsJsonObject().get("categoryname").toString().replaceAll("\"", ""));
                        Log.i("LOG", "downloadCategories response: " + incomingDataSet.toString());
                    }

                } else {
                    Log.i("LOG", "Response error: " + response.code());
                }
            })
    );

    Log.i("LOG", "getCat: " + incomingDataSet.toString());
    
    return incomingDataSet;
}

MainActivity:主要活动:

List<String> categorylist = new ArrayList<>();
categorylist = netWorker.getCat();
Log.i("LOG", "list:" + categorylist );

So, what I see in log:所以,我在日志中看到的:

First:第一的:

getCat: []获取猫:[]

list: []列表: []

and then:进而:

downloadCategories response: [cat1]下载类别响应:[cat1]

downloadCategories response: [cat1, cat2]下载类别响应:[cat1, cat2]

downloadCategories response: [cat1, cat2, cat3]下载类别响应:[cat1, cat2, cat3]

Show spinner in doOnSubscribe() and hide in doFinally() .显示在doOnSubscribe微调()和隐藏在doFinally()。 Put code that fills RecyclerView inside subscribe() to fill it when data arrives.将填充RecyclerView 的代码放入subscribe()以在数据到达时填充它。 Otherwise you just get empty new list on Main thread and do not update RecyclerView further.否则,您只会在主线程上获得空的新列表,并且不会进一步更新RecyclerView

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM