Muhamed Raafat
Muhamed Raafat

Reputation: 277

Android custom dialog with MVVM

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

Upvotes: 1

Views: 8357

Answers (1)

Riddhi Shah
Riddhi Shah

Reputation: 3122

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

Upvotes: 3

Related Questions