Replace listeners with RxJava

2

I am beginning to know the advantages of RxJava, and I would like someone to lend me a hand to get to the point.

The issue would be to modify this code made with listeners:

public void getData( final OnResponseListener listener ){
    if(data!=null && !data.isEmpty()){
        listener.onSuccess();
    }
    else{
        listener.onError();
    }
}

Listener:

public interface OnResponseListener {

    public void onSuccess();

    public void onError(); 
}

And the one who listens:

 object.getData( new OnResponseListener() {
            @Override
            public void onSuccess() {
                Log.w(TAG," on success");
            }

            @Override
            public void onError() {
                Log.e(TAG," on error");
            }
        });

How to do this with observables? Thanks

    
asked by Pablo Cegarra 07.02.2017 в 17:35
source

1 answer

0

The solution I am using is the following:

public static Single<List<Data>> getData() {

        return Single.create(singleSubscriber -> {

                if(data!=null){
                    singleSubscriber.onSuccess(data);
                }
                else{
                    singleSubscriber.onError(new Exception("no data"));
                }
            });
        });
    }

And to receive the data:

 Single<List<Data>> data = Api.getData();
        data.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<List<Data>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onSuccess(List<Data> data) {
                        mAdapter.addItems(data);
                    }

                    @Override
                    public void onError(Throwable e) {
                        showError();
                    }
                });
    }
    
answered by 13.02.2017 / 19:32
source