Skip to content

Should Maybe.flatMapSingle return a Maybe? #4857

@perlow

Description

@perlow

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"));
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions