-1

I have a list of ids, and have a method which takes an id and return Observable<Boolean>, it is doing an operation using the ID and return true if success.

let's say that I have user id (1), and I need to update his profile with this method Observable<Boolean> updateProfile(int id) , that's ok and working fine.

what I need now is creating method for multiple id's, and if all profiles are updated return true. it may has this signature Observable<Boolean> updateAllProfiles(int[] ids)

How to achieve something like this?

Mohamed Ibrahim
  • 3,714
  • 2
  • 22
  • 44

2 Answers2

3

Assuming you want to update each profile separately and return true after all updates end, you can use combination of flatMap and reduce:

Observable<Boolean> updateAllProfiles(Integer[] ids) {
    return Observable.from(ids)
            .flatMap(id -> updateProfile(id))
            .reduce((prevResult, currResult) -> prevResult && currResult);
}

and the use:

updateAllProfiles(new Integer[]{0, 1, 2, 3, 4})
            .subscribe(updateAllSucceed -> { //do something with result});

this will fire all update in parallel (assuming each update profile will act on Scheduler.io or alike that create new thread) and will accumulate all results indication and return true/false accordingly.
BTW, you might want to consider Completable instead of Observable<Boolean> which is well suits to 'void' update methods (you can read my explanation here)

Community
  • 1
  • 1
yosriz
  • 10,147
  • 2
  • 24
  • 38
0
  Observable<Boolean> updateAllProfiles(Integer[] ids) {
    return Observable.from(ids)
        .flatMap(id -> updateProfile(id))
        .all(success-> success);
  }
Dean Xu
  • 4,438
  • 1
  • 17
  • 44