title: RXjava and Retrofit to handle empty data response
body: <p>I use Rxjava and Retrofit to handle the response from an HTTP server.</p>
  <p>Most of the time, data response is in this format:</p>
  <pre><code>{
    code: 'OK',
    data: {.....}
  }
  </code></pre>
  <p>And sometimes, the <code>data</code> property doesn't exist:</p>
  <pre><code>{
    code: 'OK'
  }
  </code></pre>
  <p>I make a <code>BaseResponse</code> class.</p>
  <pre><code>public class BaseResponse&lt;T&gt; implements Serializable {
      private String code;
      private String msg;
      private T data;
  
      public String getCode() {
          return code;
      }
  
      public String getMsg() {
          return msg;
      }
  
      public T getData() {
          return data;
      }
  }
  </code></pre>
  <p>And make a <code>Map</code> function to parse it:</p>
  <pre><code>public static &lt;T&gt; Function&lt;BaseResponse&lt;T&gt;, T&gt; applyUnwrapResponse () {
          return new Function&lt;BaseResponse&lt;T&gt;, T&gt;() {
              @Override
              public T apply(@NonNull BaseResponse&lt;T&gt; baseResponse) throws Exception {
                  if (baseResponse.getCode().equals(Constants.SUCCESS_CODE)) {
                      // http returned from server
                      T data = baseResponse.getData();
                      if (data == null) {
                          return null;  // throw exception: The mapper function returned a null value
                          return return new T(); // syntax error
                          // how ?
                      }
                      return data;
                  } else if (baseResponse.getCode().equals(Constants.USER_NOT_LOGGED_IN)) {
                      // auth token error
                      throw new UserNotLoginException(baseResponse.getMsg());
                  }
                  // unknown error
                  throw new UnknownServerException(baseResponse.getMsg());
              }
          };
      }
  </code></pre>
  <p>When <code>data</code> property doesn't exist, I try to return <code>null</code>, but this is not allowed in <a href="https://github.com/ReactiveX/RxJava/wiki/What%27s-different-in-2.0#nulls" rel="nofollow noreferrer">Rxjava2</a>.<br />
  In the customize Observer, I handle all <code>success</code> scenarios in onNext(), so I need to emit an error when <code>data == null</code>.<br />
  but I can not return null, and also cannot return a <code>T</code> by <code>return new T()</code>, so how should I do? Anyone can help me out?</p>