Shvalb
Shvalb

Reputation: 1933

How to avoid nested subscribe when working with mixed Maybe and Single

I have come a cross the following requirement:

I have a method that returns Maybe and I need to process it in a away that if it returns something then Invoke another method that returns Single, otherwise on the OnComplete invoke Single.

Here is an Snippet:

 doSomethingThatReturnsMaybe()
 .flatMapSingleElement(obj-> {
     return doSomethingThatReturnsSingle();
 })
 .subscribe(obj -> LOG.info(obj),
  err -> LOG.err("", err),
  () -> {
     doSomethingThatReturnsSingle()
     .subscribe();
  });

Any idea how to get rid of the nested subscribe ?

UPDATE: Latest Code Snippet

doSomethingThatReturnsMaybe()
  .flatMapSingleElement(obj-> {
    return doSomethingThatReturnsSingle();
  })
  .switchIfEmpty(doSomethingElseThatReturnsSingle())
  .subscribe(obj -> LOG.info(obj),
         err -> LOG.err("", err);

Upvotes: 1

Views: 243

Answers (2)

Shubha
Shubha

Reputation: 55

If I am understanding it correctly, then in both the cases(whether Maybe is empty or not), you wanna call the doSomethingThatReturnsSingle(). If it is so, below code might help,

doSomethingThatReturnsMaybe().isEmpty()
                             .flatMap(isEmpty-> doSomethingThatReturnsSingle())
                             .subscribe(obj-> System.out.println(obj));

Upvotes: 0

Fred
Fred

Reputation: 17095

Following the discussion on the comments, I feel like this could be a solution.

I'd use switchIfEmpty here.

Something like:

doSomethingThatReturnsMaybe()
  .flatMapSingleElement(obj-> {
    return doSomethingThatReturnsSingle();
  })
  .switchIfEmpty(doSomethingThatReturnsSingle())
  .subscribe(obj -> LOG.info(obj),
             err -> LOG.err("", err);

switchIfEmpty will execute if the Maybe returns empty. Note, this is different than what you had. What you had executes doSomethingThatReturnsSingle() twice. This new example executes it once. If the maybe returns empty the switchIfEmpty will run it once, otherwise, it runs on the flatMapSingleElement. Before it was also running once the stream completed.

Upvotes: 1

Related Questions