本文介紹了用RxJava替換異步任務(wù)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我一直在學(xué)習(xí)如何使用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風(fēng)格編寫:
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();
}
如果您關(guān)心結(jié)果,可以在subscribe()
方法中添加更多回調(diào):
.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() {
}
});
這篇關(guān)于用RxJava替換異步任務(wù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,