Is there a way I can return user list from userObservable in the below code. Basically how to read object values of an Observable.
public List<User> getUserList(){
Observable<Map<String, Object>> userDetailsObservable = getUserDetails(...);
Observable<Map<String, Object>> userLikesObservable = getUserLikes(...);
Observable<List<User>> userObservable = Observable.zip(userDetailsObservable,
userLikesObservable, new Func2<Map<String, Object>, Map<String, Object>, List<User>>() {
public List<User> call(Map<String, Object> value1, Map<String, Object> value2) {
List<User> userList = new ArrayList<User>();
//Iterating both maps and composing user list here.
return userList;
}
});
userObservable.subscribe(new Subscriber<List<User>>() {
@Override
public void onNext(List<User> userList) {
System.out.println("Merged values " + userList);
}
@Override
public void onError(Throwable error) {
System.err.println("Error: " + error.getMessage());
}
@Override
public void onCompleted() {
System.out.println("Sequence complete.");
}
});
// Throws ClassCastException which is expected... How do I get the user list from userObservable
List<User> userList = List<User> userObservable;
return userList; //Fetch the user list from userObservable and return
}
You need to subscribe to the userObservable
. You will then get a list of users emitted when the data becomes available.
userObservable
.subscribe(users -> {
for (User user : users) {
// Do what you want with user.
}
});
EDIT: To return the list you would need to use a toBlocking()
call. Then you can use one of the Blocking Observable Operators to get the desired effect. Most likely first()
or single()
will work for you.
return userObservable
.toBlocking()
.first();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With