我一直在尝试学习如何使用RXJava,我想知道如何更改下面的异步任务代码并使用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() {
}
});