Reputation: 2160
I use RxJava in my Android project, I want to retrieve all entities User from a table using RxJava asynchronously and return the list List to an adapter myAdapter(Context context, List<User> users)
.
But now I can only have Single<User>
, how can I get the list directly and put it into my adapter ?
My code:
// here vm.getUserList() should return a List<User>
MyAdapter adapter = new MyAdapter(context, vm.getUserList());
...
And in my vm:
public Single<List<User>> getUserList() {
return Single.fromCallable(() -> myDatabaseRepository.getUsers());
}
Upvotes: 1
Views: 744
Reputation: 660
You only need to call the users method and handle the success/error in the corresponding method.
getUserList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess(new Consumer<List<User>>() {
@Override
public void accept(List<User> users) throws Exception {
// fill adapter
MyAdapter adapter = new MyAdapter(context, users);
}
})
.doOnError(new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
// handle error
}
});
Yes, this is the normal way of retrieving the data from the database/network. You expose from the repository the Observables/Singles, then you subscribe to them and receive the data in the success/error methods to show in the UI to the user.
Upvotes: 1
Reputation: 1274
private void fetchUser() {
('function returning Single<List<User>>').subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onSuccess, this::onFail);
}
private void onSuccess(List<User> users) {
//handle user model here
}
private void onFail(Throwable t) {
//handle error here
}
Upvotes: 0