aws-amplifyaws-amplify-sdk-android

How to get a List<T> of items for a RecyclerView?


I'm getting started with the Amplify Framework and I'm following Building an Android app with AWS Amplify – Part 1 from the AWS blog. The code being used there appears to be outdated (2018) since there's nothing like that in the Amplify Libraries.

I'm stuck at the part where I need to display a RecyclerView of items. In that article, you can get the items like this:

response.data().listPets().items()

However, in the current docs, there's a response.getData() method which returns an Iterator<T>, that you can loop through.

What I'd like is to get a List<T> to feed a RecyclerView.Adapter.

Please advise.


Solution

  • I was following through the latest implementations in Amplify , using the RxAmplify and a sample todo application, which internally uses rxJava. So I used the below code to query through the datastore and obtain a list of values which can be used to update the recyclerview adapter. The

    toList()

    part converts the query results to list which can be used in the adapter.

    RxAmplify.DataStore.query(Todo.class)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .toList()
                .subscribe(todolist->{
                    adapter.updateList(todolist);
                    adapter.notifyDataSetChanged();
                });
    

    The part

    .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread())

    is important else you wouldn't be able to access the UI, and will throw exception.