ViewModel for fragment

Viewed 1317

I am applying MVVM pattern in native Android development. I have a LoginActivity and it will host two different fragments that are LoginFragment and RegisterFragment. I am not sure what to do in this case. A viewModel for the LoginActivity or two different ViewModel for two fragments. If I create one viewModel for activity, login and register view bindings and logics will mix up with each other. But in many tutorials developers are saying that we should create one viewmodel per activity and access those viewmodels from fragment. How should I handle things here?

My login fragment if necessary

public class LoginFragment extends Fragment {
private LoginViewModel loginViewModel;

public LoginFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    FragmentLoginBinding fragmentLoginBinding = DataBindingUtil.setContentView(getActivity(), R.layout.fragment_login);
    loginViewModel = ViewModelProviders.of(this, new LoginViewModelFactory(getActivity().getApplication(),
            LoginRepository.getInstance())).get(LoginViewModel.class);
    fragmentLoginBinding.setViewModel(loginViewModel);
    fragmentLoginBinding.executePendingBindings();
    return inflater.inflate(R.layout.fragment_login, container, false);
}
} 

and LoginActivity

public class LoginActivity extends AppCompatActivity {
private LoginViewModel loginViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    FragmentUtil.replaceFragment(getSupportFragmentManager(), R.id.entry_frame, new LoginFragment(), "login");
} 
}
2 Answers

One way to access the Activity ViewModel is by calling getActivity in the Fragment, then casting it to the Class that you have and accessing the PUBLIC viewModel property.

I don't know your exact usecase but I might use multiple Fragments and have a repository above those that has some of the shared logic.

You can take away some of the boilerplate of multiple Fragments by doing them like so:

https://itnext.io/get-rid-of-fragment-activity-boilerplate-code-using-kotlin-1b103763baf8?sk=a4b037902f0fe4bfdec10cc9cc814426

In my opinion, you should create two different ViewModel. Because, ViewModel is designed to store and manage UI-related data in a lifecycle of Activity or Fragment. Do that help you independent and easy to management logic.

If you want to share data between fragment and activity or fragment and fragment, you can see:

Related