如何使用lambda提取rxjava的onError方法

时间:2015-05-20 08:46:19

标签: android lambda rx-java

我有网络要求:

userApi.getUserInfoByUid (AuthUtils.getUid (ctx), AuthUtils.getToken (ctx))
            .doOnNext (u -> saveToCache (u))
            .observeOn (AndroidSchedulers.mainThread ())
            .subscribe (u -> {
                if (updateListener != null)
                    updateListener.onUpdate (u);
            },e->{
                Toast.makeText (ctx,"network error",Toast.LENGTH_SHORT).show ();
            });

你知道,许多请求可能有网络错误,所以我提取OnError()方法。如:

 abstract class Mysubscrib<T> extends Subscriber<T>{

    @Override
    public void onCompleted() {
        //do nothing
    }

    @Override
    public void onError(Throwable e) {
        Toast.makeText (ctx,"network error",Toast.LENGTH_SHORT).show ();
    }
}

    userApi.getUserInfoByUid (AuthUtils.getUid (ctx), AuthUtils.getToken (ctx))
            .doOnNext (u -> saveToCache (u))
            .observeOn (AndroidSchedulers.mainThread ())
            .subscribe (new Mysubscrib<UserInfo> () {
                @Override
                public void onNext(UserInfo userInfo) {
                    if (updateListener != null)
                        updateListener.onUpdate (userInfo);
                }
            });

但如果我这样做,我就不能使用lambda,感觉很糟糕。我可以使用:

userApi.getUserInfoByUid (AuthUtils.getUid (ctx), AuthUtils.getToken (ctx))
            .doOnNext (u -> saveToCache (u))
            .observeOn (AndroidSchedulers.mainThread ())
            .subscribe (u->{
                if (updateListener != null)
                    updateListener.onUpdate (u);
            });

1 个答案:

答案 0 :(得分:5)

不幸的是,java及其lambda表达式不允许这样做。解决此问题的最简单方法是为Mysubscrib提供另一个接受Action1作为参数的工厂方法:

abstract class Mysubscrib<T> extends Subscriber<T> {
    public static <T> Mysubscrib<T> create(final Action1<? super T> action) {
        return new Mysubscrib<T>() {
            @Override
            public onNext(final T value) {
                action.call(value);
            }
        }
    }

    @Override
    public void onCompleted() {
        //do nothing
    }

    @Override
    public void onError(Throwable e) {
        Toast.makeText (ctx,"network error",Toast.LENGTH_SHORT).show ();
    }
}

用法:

userApi.getUserInfoByUid (AuthUtils.getUid (ctx), AuthUtils.getToken (ctx))
        .doOnNext (u -> saveToCache (u))
        .observeOn (AndroidSchedulers.mainThread ())
        .subscribe (Mysubscrib.create(u -> {
            if (updateListener != null)
                updateListener.onUpdate (u);
        });