为什么LiveData Observer被调用太多次?

时间:2019-02-11 08:59:20

标签: java android android-room android-livedata

我正在将Android LiveData与Room数据库一起使用。 一切正常,但唯一的问题是LiveData观察器被调用了太多次。 我在Activity onCreate函数中初始化了ViewModel。 请检查我的代码,如果我做错了什么。 谢谢

viewModel = ViewModelProviders.of(this).get(PersonListViewModel.class);
viewModel.getAll().observe(this, personList->{
    Log.e("PersonRecycler", "Observer called");

    if (personList.size() == 0) {
        lytNoPerson.setVisibility(View.VISIBLE);
    } else {
        lytNoPerson.setVisibility(View.GONE);
        adapterData.resetData(personList);
    }
});

我希望这个观察者在第一次加载时只调用一次。 每当我有新的更新时再打一次。 但是它在第一次加载时调用了很多次。 请在下面查看此屏幕截图。 再次感谢。

http://prntscr.com/mjg7dw

下面是ViewModel源代码。

public class PersonListViewModel extends AndroidViewModel {
    private PersonRepository repository;

    private MutableLiveData<List<Person>> personList;
    private MediatorLiveData<List<Person>> liveDataMerger;

    public PersonListViewModel(@NonNull Application application) {
        super(application);

        repository = PersonRepository.getInstance(application);

        personList = new MutableLiveData<>();
        liveDataMerger = new MediatorLiveData<>();
    }

    public LiveData<List<Person>> getAll() {
        String createdBy = AppController.getInstance().firebaseUser.getEmail();
        return repository.getAll(createdBy);
    }

    public LiveData<PagedList<Person>> getPagedPerson() {
        return repository.getPagedPerson();
    }

    public LiveData<List<Person>> loadMore(int page) {
        /*
        LiveData<List<Person>> pList = repository.getPersonByPage(page);
        liveDataMerger.addSource(pList, list->{
            liveDataMerger.setValue(list);
        });

        return liveDataMerger;
        */
        return repository.getPersonByPage(page);
    }

    public MutableLiveData<List<Person>> getPersonList() {
        return personList;
    }
}

这是存储库中的getAll函数。

public LiveData<List<Person>> getAll(String createdBy) {
        return database.personDao().getAll(createdBy);
    }

这是Dao中的getAll函数

@Query("SELECT * FROM " + TABLE_PERSON + " WHERE deleted=0 AND createdBy=:createdBy ORDER BY created DESC")
LiveData<List<Person>> getAll(String createdBy);

0 个答案:

没有答案
相关问题