Alex Kornakov
Alex Kornakov

Reputation: 313

How do I refactor common map for Single/Observable inside of if block

How can I refactor this piece of code? If I move .map() out of flatMapSingle I'll lose id.

Observable.fromArray(1, 2, 3)
          .flatMapSingle(id -> {
              if (id % 2 == 0)
              {
                  return loadObjectSingle(id)
                        .map(object -> Entry(id, object));
              }
              else
              {
                  return loadFakeObjectSingle(id)
                          .map(object -> Entry(id, object));
              }
          })

Upvotes: 2

Views: 43

Answers (1)

Dave Moten
Dave Moten

Reputation: 12097

Just assign the single so you only do the map once.

Observable
  .fromArray(1, 2, 3)
  .flatMapSingle(id -> {
     Single<T> single;
     if (id % 2 == 0) {
        single = loadObjectSingle(id);
     } else {
        single = loadFakeObjectSingle(id);
     }
     return single.map(object -> Entry(id, object));
   });

Upvotes: 1

Related Questions