JaviBear
JaviBear

Reputation: 1

Asynchronously updating a ListView

I'm dealing with the following api call https://pokeapi.co/api/v2/pokemon/, the problem is that it seems quite slow and each entry has itself several endpoints. Is it possible to update ListView asynchronously while making the api calls? I feel that it will probably be something like using the endpoint's next and previous keys and triggering listener events that update the Listview from the AsyncTask's doInBackground or onProgressUpdate methods. I'd appreciate any help, I feel that I have the beginning of an idea, but I need help finishing the thought.

Upvotes: 0

Views: 65

Answers (1)

Paresh Mayani
Paresh Mayani

Reputation: 128428

You can definitely implement it through AsyncTask but I would rather suggest a solution using RxJava.

You can implement RxJava Chaining.

Sharing a code snippet how you can make a chaining call using RxJava.

 private void fetchHackerNewsStoriesChaining() {

        StoriesApiInterface storiesApiInterface = HackerNewsApiClient.getStoriesApiInterface();
        storiesApiInterface.getTopStories()
                .flatMapIterable(new Function<JsonArray, Iterable<?>>() {
                    @Override
                    public Iterable<?> apply(JsonArray jsonArray) throws Exception {
                        Log.d("Count", ""+jsonArray.size());
                        return jsonArray;
                    }
                })
                .flatMap(new Function<Object, ObservableSource<SingleStoryModelResponse>>() {
                    @Override
                    public ObservableSource<SingleStoryModelResponse> apply(Object newsId) throws Exception {

                        return HackerNewsApiClient.getStoryDetailsApiInterface().getNewsStoryDetail(((JsonElement) newsId).getAsLong())
                                .subscribeOn(Schedulers.io());
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<SingleStoryModelResponse>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        progressBar.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onNext(SingleStoryModelResponse singleStoryModelResponse) {
                        adapterNewsList.addNewsItem(singleStoryModelResponse);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("Hacker News", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        progressBar.setVisibility(View.GONE);
                    }
                });
    }

Upvotes: 1

Related Questions