Sala - O observador do LiveData não é acionado quando o banco de dados é atualizado
Estou tentando descobrir no código abaixo, por que o LiveData observável do Room não me dá novos turnos depois de preencher o banco de dados com novos dados.
Isso é colocado no método onCreate da minha atividade:
shiftsViewModel = ViewModelProviders.of(this).get(ShiftsViewModel.class);
shiftsViewModel
.getShifts()
.observe(this, this::populateAdapter);
Este é o método populateAdapter:
private void populateAdapter(@NonNull final List<Shift> shifts){
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(shifts));
}
Também tenho o seguinte código que preenche o banco de dados (eu uso o RxJava para fazer o trabalho em um thread de E / S, pois o Room precisa que seu código seja chamado fora do thread principal):
@Override
public Observable<List<Shift>> persistShifts(@NonNull final List<Shift> shifts){
return Observable.fromCallable(() -> {
appDatabase.getShiftDao().insertAll(shifts);
return shifts;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
O problema que tenho ocorre quando chamo persistShifts depois de começar a observar meus shiftsViewModel. Eu esperaria que meu observador (LiveData) fosse acionado com todos os turnos adicionados recentemente. Acontece que o observador é acionado, mas uma lista vazia de turnos é retornada. A única maneira de fazê-lo "funcionar" é se eu deixar a atividade (portanto destruindo o ViewModel atual) e entrar novamente. Desta vez, o LiveData do viewModel fornece todas as mudanças que persistiram anteriormente, conforme o esperado.
Aqui está o restante do código:
@Entity
public class Shift{
@PrimaryKey
private long id;
private String start;
private String end;
private String startLatitude;
private String startLongitude;
private String endLatitude;
private String endLongitude;
private String image;
...
DAO:
@Dao
public interface ShiftDAO {
@Query("SELECT * FROM shift")
LiveData<List<Shift>> getAll();
@Query("SELECT * FROM shift WHERE id = :id")
LiveData<Shift> getShiftById(long id);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<Shift> shifts);
}
ViewModel:
public class ShiftsViewModel extends AndroidViewModel{
private final ISQLDatabase sqlDatabase;
private MutableLiveData<Shift> currentShift;
private LiveData<List<Shift>> shifts;
private boolean firstTimeCreated;
public ShiftsViewModel(final Application application){
super(application);
this.sqlDatabase = ((ThisApplication) application).getSQLDatabase();
this.firstTimeCreated = true;
}
public MutableLiveData<Shift> getCurrentlySelectedShift(){
if(currentShift == null){
currentShift = new MutableLiveData<>();
}
return currentShift;
}
public LiveData<List<Shift>> getShifts() {
if(shifts == null){
shifts = sqlDatabase.queryAllShifts();
}
return shifts;
}
public void setCurrentlySelectedShift(final Shift shift){
currentShift = getCurrentlySelectedShift();
currentShift.setValue(shift);
}
public boolean isFirstTimeCreated(){
return firstTimeCreated;
}
public void alreadyUsed(){
firstTimeCreated = false;
}
}
Por que não estou recebendo a lista de turnos que persisto no retorno de chamada observe () imediatamente?