作者:俣宸爸555_872_923 | 来源:互联网 | 2023-01-21 13:07
1> joao86..:
好吧,我已经找到了解决这个问题的方法,并了解了这个LiveData的工作原理.
感谢@MartinMarconcini,他的所有帮助都是调试;)
显然,观察者与您首次设置的对象相关联.您无法替换对象(通过归因),否则将无法使用.此外,如果您的变量的值将要更改,那么您应该使用MutableLiveData
所以必要的改变是:
1.从LiveData更改为MutableLiveData,并在需要更新时将MutableLiveData传递给存储库
public class StatesViewModel extends ViewModel {
private MutableLiveData> states; ;;CHANGED
private StatesRepository repo;
@Inject
public StatesViewModel(StatesRepository repository){
this.repo = repository;
}
public void init(String token){
states = repo.getStates(token);
}
public void getStatesFromCountry(String countryID){
repo.getStatesFromCountry(this.states, countryID); ;;CHANGED
}
public LiveData> getStates(){
return this.states;
}
}
2.在存储库中,使用setValue更新MutableLiveData
@Singleton
public class StatesRepository {
private final WebServices services;
private final StateDao stateDao;
private final Executor executor;
@Inject
public StatesRepository(Executor executor, StateDao stateDao, WebServices services) {
this.services = services;
this.stateDao = stateDao;
this.executor = executor;
}
public MutableLiveData> getStates(String token){
refreshStates(token);
final MutableLiveData> data = new MutableLiveData<>();
data.setValue(stateDao.getAllStates());
return data;
}
;; CHANGED
public void getStatesFromCountry(MutableLiveData states, final String countryID){
states.setValue(stateDao.getStatesFromCountry(countryID));
}
private void refreshStates(final String token){
executor.execute(() -> {
if(stateDao.getNrStates() == 0){
try {
Response> respOnse= services.getStates("Bearer "+token).execute();
stateDao.insertAll(response.body());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
3.将DAO更改为返回List而不是LiveData>
@Dao
public interface StateDao {
@Query("SELECT * FROM states")
List getAllStates();
@Query("SELECT * FROM states WHERE ctrId = :countryID")
List getStatesFromCountry(String countryID);
@Query("SELECT COUNT(*) FROM states")
int getNrStates();
@Query("SELECT COUNT(*) FROM states WHERE ctrId = :countryID")
int getNrStatesByCountry(String countryID);
@Insert(OnConflict= IGNORE)
void insertAll(List states);
@Delete
void delete(State state);
}
4.最后允许在主线程中执行查询
AppModule.java
@Singleton @Provides
AppDatabase provideDb(Application app) {
return Room.databaseBuilder(app, AppDatabase.class,"unitail.db")
.allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
}
有趣.那个&#39;allowMainThreadQueries()`不应该真的用于Prod ...我仍然感到困惑为什么**我直接从DAO返回LiveData而你必须改变那个......嗯.哦,很高兴听到它有效.祝好运!