Android custom dialog with MVVM

↘锁芯ラ 提交于 2019-12-25 18:57:22

问题


I am creating custom dialog and i want when the user click add button go and call retrofit and observe on changes but i don't know how to pass lifecycleowner to the observer

 private void observeViewModel(ProjectListViewModel viewModel) {
        // Update the list when the data changes
        viewModel.getProjectListObservable().observe( ***what to pass here ??*** , new Observer<List<Project>>() {
            @Override
            public void onChanged(@Nullable List<Project> projects) {
                if (projects != null) {
                    //…
                    projectAdapter.setProjectList(projects);
                }
            }
});

thanks in advance


回答1:


Try this solution. It worked for me.

Create a field of your activity from where you are calling the dialog and pass this in place of lifecycleowner

public class YourDialog extends DialogFragment {

private YourActivity activity;

    public static YourDialog newInstance(YourActivity activity) {
        YourDialog dialog = new YourDialog();
        dialog.activity = activity;
        return dialog;
    }

    private void observeViewModel(ProjectListViewModel viewModel) {
    // Update the list when the data changes
    viewModel.getProjectListObservable().observe( activity , new Observer<List<Project>>() {
        @Override
        public void onChanged(@Nullable List<Project> projects) {
            if (projects != null) {
                //…
                projectAdapter.setProjectList(projects);
            }
        }
    });

}

You can refer the example of mvvm here if you want



来源:https://stackoverflow.com/questions/49878279/android-custom-dialog-with-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!