我需要借助Room等工具将数据插入数据库。这是我的操作方式:
这是我的DAO
界面
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
import io.reactivex.Completable;
import io.reactivex.Observable;
@Dao
public interface MovieDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
Completable insertMovie(final MovieEntity movie);
}
这是应该将数据添加到db的方法:
@Override
public void addMovieToFavorites(@Nonnull Bundle bundle) {
String url = bundle.getString(MovieListFragment.EXTRA_IMAGE);
int watchers = bundle.getInt(MovieDetailActivity.EXTRA_WATCHERS);
String name = bundle.getString(MovieDetailActivity.EXTRA_NAME);
MovieDatabase database = TraktTvApp.getInstance().getDatabase();
MovieDao movieDao = database.movieDao();
MovieEntity movieEntity = new MovieEntity(name, watchers, url);
mCompositeDisposable.add(Observable.fromCallable(() ->
movieDao.insertMovie(movieEntity))
.doOnSubscribe(disposable -> mView.showLoadingIndicator(true))
.doOnError(throwable -> mView.onMovieDetailsFailed())
.doOnComplete(() -> mView.onMoviesAdded())
.doOnTerminate(() -> mView.showLoadingIndicator(false))
.observeOn(Schedulers.io())
.subscribe()
);
}
但是不幸的是,正如我在Stetho中看到的那样,数据没有添加到db中。那怎么了我要添加的数据不为null,并且运行时没有错误(如onComplete方法被调用)。我认为rx逻辑存在问题,但我是其中的新手,无法理解为什么会发生我的问题
UPD
我通过以下方式更改了接收逻辑:
mCompositeDisposable.add(Observable.fromCallable(() -> movieDao.insertMovie(movieEntity))
.subscribeOn(Schedulers.io())
.doOnSubscribe(disposable -> mView.showLoadingIndicator(true))
.observeOn(AndroidSchedulers.mainThread())
.doOnError(throwable -> mView.onMovieDetailsFailed())
.doOnComplete(() -> mView.onMoviesAdded())
.doAfterTerminate(() -> mView.showLoadingIndicator(false))
.subscribe()
);
但是它仍然不起作用
UPD 2
mCompositeDisposable.add(movieDao.insertMovie(movieEntity)
.subscribeOn(Schedulers.io())
.doOnSubscribe(disposable -> mView.showLoadingIndicator(true))
.observeOn(AndroidSchedulers.mainThread())
.doOnError(throwable -> mView.onMovieDetailsFailed())
.doOnComplete(() -> mView.onMoviesAdded())
.doAfterTerminate(() -> mView.showLoadingIndicator(false))
.subscribe()
);