用RxJava替换异步任务

Replace Async Task with RxJava(用RxJava替换异步任务)

本文介绍了用RxJava替换异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习如何使用RXJava,我想知道如何更改下面的AsyncTask代码并使用RXJava,这是可能的吗?我不熟悉RXJava,由于AsyncTask已被弃用,我需要一些帮助。
 private static class AddTeamAsyncTask extends AsyncTask<Team, Void, Void> {
        private TeamDao teamDao;
         AddTeamAsyncTask(TeamDao teamDao) {
            this.teamDao = teamDao;
        }

        @Override
        protected Void doInBackground(Team... teams) {
            teamDao.addTeam(teams[0]);
            return null;
        }
    }

推荐答案

RxJava非常简单。你可以这样写:

private void addTeamInBackground(Team team) {
    Observable.fromCallable(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            teamDao.addTeam(team);
            // RxJava does not accept null return value. Null will be treated as a failure.
            // So just make it return true.
            return true;
        }
    }) // Execute in IO thread, i.e. background thread.
        .subscribeOn(Schedulers.io())
        // report or post the result to main thread.
        .observeOn(AndroidSchedulers.mainThread())
        // execute this RxJava
        .subscribe();
}

也可以用Java 8 Lambda风格编写:

private void addTeamInBackground(Team team) {
    Observable.fromCallable(() -> {
        teamDao.addTeam(team);
        // RxJava does not accept null return value. Null will be treated as a failure.
        // So just make it return true.
        return true;
    }) // Execute in IO thread, i.e. background thread.
        .subscribeOn(Schedulers.io())
        // report or post the result to main thread.
        .observeOn(AndroidSchedulers.mainThread())
        // execute this RxJava
        .subscribe();
}

如果您关心结果,可以在subscribe()方法中添加更多回调:

        .subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean success) {
                // on success. Called on main thread, as defined in .observeOn(AndroidSchedulers.mainThread())
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

这篇关于用RxJava替换异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:用RxJava替换异步任务

基础教程推荐