Rxjava: Should Maybe.flatMapSingle return a Maybe?

Created on 16 Nov 2016  路  3Comments  路  Source: ReactiveX/RxJava

I am converting from RX1 and I am wondering why the decision was made for Observable.flatMapSingle to return an Observable whereas Maybe.flatMapSingle returns a Single. I have the case below where my intuition is that Maybe.flatMapSingle should return a Maybe. The reason is that this is guaranteed to throw if the Maybe actually works like a Maybe and is sometimes empty. If that is the desire of the caller, it seems like they should explicitly request for that behavior by using maybe.toSingle().flatMap(...). I think most callers of maybe.flatMapSingle will expect an empty Maybe to pass through an empty Maybe. This is how it would work with Observable.flatMapSingle where each result passed through the map emits a result through the Observable and it works as expected

interface User {
  Single<Boolean> isUserEmployee();
}

class PermissionRules {

  /**
   * Allows permission if the User is an employee. Otherwise, is empty so that you
   * can use {@link Maybe#switchIfEmpty} for the next condition.
   *
   * @param user the user to check
   * @return the permission result (allowed or empty)
   */
  public static Maybe<PermissionResult> allowIfEmployee(Maybe<User> user) {
    // !!! Does not work if user is empty 
    return user
      .flatMapSingle(User::isEmployee)
      .compose(PermissionResult.allowIfTrue("Allowed because user is an employee"));
  }
}
2.x Feature-Request

Most helpful comment

We can't change that return type but we can introduce a flatMapSingleElement() operator just like there is single() and singleElement.

All 3 comments

We can't change that return type but we can introduce a flatMapSingleElement() operator just like there is single() and singleElement.

See #4858

Closing via #4858

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ljf1172361058 picture ljf1172361058  路  3Comments

midnight-wonderer picture midnight-wonderer  路  3Comments

Jaap-van-Hengstum picture Jaap-van-Hengstum  路  3Comments

archenroot picture archenroot  路  3Comments

SammyVimes picture SammyVimes  路  4Comments