简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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