【问题标题】:How to wait/observe incoming data from server correctly with rxjava/retrofit如何使用 rxjava/retrofit 正确等待/观察来自服务器的传入数据
【发布时间】:2021-02-04 19:44:40
【问题描述】:

我在从服务器下载数据时遇到问题,更具体地说,我无法实现“等待/观察传入数据”行为。我想用来自服务器的列表填充我的RecyclerView 和Spinner,但是知道,这些方法返回空/空列表。我明白了,问题是方法在数据到达之前完成。

我检查了这两个相似的问题,但没有一个答案对我有用:

Waiting for API Calls to complete with RxJava and Retrofit

RXJava retrofit waiting having the UI wait for data to be fetched from API

我的代码:

API:

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

网络工作者:

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

主活动:

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

那么,我在日志中看到的:

第一:

getCat: []

列表:[]

然后:

downloadCategories 响应:[cat1]

downloadCategories 响应:[cat1, cat2]

downloadCategories 响应:[cat1, cat2, cat3]

【问题讨论】:

    标签: android retrofit rx-java2


    【解决方案1】:

    在 doOnSubscribe() 中显示微调器并在 doFinally() 中隐藏。将填充 RecyclerView 的代码放入 subscribe() 中,以便在数据到达时填充它。否则,您只会在主线程上获得空的新列表,并且不会进一步更新 RecyclerView。

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 2018-10-26
      • 1970-01-01
      • 2014-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 2020-11-21
      相关资源
      最近更新 更多