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. 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 waiting having the UI wait for data to be fetched from 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]
downloadCategories response: [cat1, cat2]
downloadCategories response: [cat1, cat2, cat3]