RxJava est assez simple. Vous pourriez l'écrire comme ceci :
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();
}
Ou vous pouvez l'écrire dans le style Lambda de Java 8 :
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();
}
Si vous vous souciez du résultat, vous pouvez ajouter d'autres rappels dans le fichier subscribe()
méthode :
.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() {
}
});