Replace callbacks with observables from RxJava

后端 未结 4 1781
醉话见心
醉话见心 2020-12-09 02:17

Im using listeners as callbacks to observe asynchronous operations with Android, but I think that could be great replacing this listeners with RxJava, Im new using this libr

4条回答
  •  情书的邮戳
    2020-12-09 02:57

    For example you can use Observable.fromCallable to create observable with your data.

    public Observable getData(){
        return Observable.fromCallable(() -> {
            Data result = null;
            //do something, get your Data object
            return result;
        });
    }
    

    then use your data

     getData().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(data -> {
                    //do something with your data
                }, error -> {
                    //do something on error
                });
    

    Used rxjava 1.x and lambda expressions.

    edit:

    if I understand you well, you wanted to replace that listener, not wrap it into observable. I added other example in reference to your comment. Oh.. also you should use Single if you are expecting only one item.

    public Single getData() {
            return Single.create(singleSubscriber -> {
                Data result = object.getData();
                if(result == null){
                    singleSubscriber.onError(new Exception("no data"));
                } else {
                    singleSubscriber.onSuccess(result);
                }
            });
        }
    
    getData().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(data -> {
                    //do something with your data
                }, error -> {
                    //do something on error
                });
    

提交回复
热议问题