【问题标题】:Not receiving the data change at LiveData未在 LiveData 收到数据更改
【发布时间】:2018-12-18 15:15:42
【问题描述】:

我正在使用一个简单的改造调用,然后更新数据,片段通过视图模型对其进行观察。 不幸的是,由于某种原因,它不起作用。这就像“postValue 或 setValue”不起作用或干脆消失了。

片段:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(requireActivity()).get(MyViewModel.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       ...
        subscribe();
        mViewModel.fetchList();

        return rootView;
    }

    private void subscribe() {
        mViewModel.getListObservable().observe(this, new Observer<List<MyObj>>() {
            @Override
            public void onChanged(@Nullable List<MyObj> objList) {
                ....
            }
        });
    }

MyViewModel:

 private LiveData<List<MyObj>> mListObservable = new MutableLiveData<>();

    private Repository repository;

    public MoviesViewModel(Application application) {
        super(application);
        repository = new Repository();
    }

    public void fetchList(){
        mListObservable = repository.getList();
    }

    public LiveData<List<MovieObj>> getListObservable(){
        return mListObservable;
    }

存储库:

public LiveData<List<MyObj>> getList(){

        final MutableLiveData<List<MovieObj>> data = new MutableLiveData<>();

        mServiceInterface.getData("en-US").enqueue(new Callback<MyResponseCustom>() {
            @Override
            public void onResponse(Call<MyResponseCustom> call, Response<MyResponseCustom> response) {
                data.postValue(response.body().getResult());
            }

            @Override
            public void onFailure(Call<MyResponseCustom> call, Throwable t) {

            }
        });

        return data;
    }

【问题讨论】:

    标签: android mvvm observable android-livedata


    【解决方案1】:

    你是RepositoryMutableLiveData的后值,但观察MyViewModelLiveData。合并它们或只使用一个

    这样试试

    MyViewModel:

    public LiveData<List<MyObj>> fetchList(){
       return repository.getList();
    }
    

    片段:

    mViewModel.fetchList().observe(this, new Observer<List<MyObj>>(){...}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多