ReactiveX / RxJava

RxJava – Reactive Extensions for the JVM – a library for composing asynchronous and event-based programs using observable sequences for the Java VM.
Apache License 2.0
47.88k stars 7.61k forks source link

Respected author,How do I avoid "The mapper function return a null value"? #6011

Closed qianshengta closed 6 years ago

qianshengta commented 6 years ago

version number

  Retrofit2              : 'com.squareup.retrofit2:retrofit:2.4.0' 
  RxAndroid2         : 'io.reactivex.rxjava2:rxandroid:2.0.2',
  RxJava2               : 'io.reactivex.rxjava2:rxjava:2.1.12',

my question

I recently encountered a problem using "RxJava2" plus "Retrofit2". I will return to the server results through a "Map", but you know, the server isn't always return a valid data, sometimes he will return "null" to me, but if I by "return" to a "Map" conversion "null", will throw an exception com.qian.qianlibrary.http.rx_http.exception.ApiException: java.lang.NullPointerException: The mapper function returned a null value. So can I do another way to return "null" to my server without throwing any exceptions?

This is my source code.

    public static Observable getObservable(Observable<HttpResponse> apiObservable) {
        Observable observable = apiObservable
                .map(new ServerResultFunction())
                .onErrorResumeNext(new HttpResultFunction<>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        return observable;
    }
public class HttpResultFunction<T> implements Function<Throwable, Observable<T>> {
    @Override
    public Observable<T> apply(@NonNull Throwable throwable) throws Exception {
        Logger.e("HttpResultFunction:" + throwable);
        return Observable.error(ExceptionEngine.handleException(throwable));
    }
}
public class ServerResultFunction implements Function<HttpResponse, Object> {
    @Override
    public Object apply(@NonNull HttpResponse response) throws Exception {

        Logger.i(response.toString());
        if (!response.isSuccess()) {
            throw new ServerException(response.getCode(), response.getMsg());
        }
        // "response. getResult ()" might be a "null",It is an "Object"
        return response.getResult();
    }
akarnokd commented 6 years ago

Please read the wiki section about nulls and pick a workaround.