Does a BottomSheetFragment need ViewModel?
Asked Answered
T

2

11

When working with Bottom Sheets and Dialog how to perform operation:

  1. Use a SharedViewModel with fragment that created this bottom sheet?
  2. Don't use a ViewModel at all?
  3. Creating a separate ViewModel for the BottomSheet?
  4. Any other approach that is best practice
Tiphane answered 29/4, 2020 at 6:46 Comment(0)
V
11
  1. If the bottom sheet/dialog is tightly bound to your "host" fragment (it shares some specific live data), and it is never going to be created from some other fragment, then it's OK to use a shared view model.
  2. If the dialog is dead simple (like one input + 2 buttons), then the viewmodel might not be needed
  3. If the dialog really needs a viewmodel (i.e. it fetches and displays some dynamic data), then a separate viewmodel makes sense
Voltameter answered 29/4, 2020 at 7:16 Comment(1)
I forgot to check you as the correct answer and it took me a while (months) to realize that ;)Tiphane
I
3

I'll go with the first approach by using a ShareViewModel, but if you understand the underlying layer, shared ViewModel is also ViewModel it's just a name convention we gave it to them.

Also sometimes it becomes tedious to write separate ViewModel to deal with fragments and bottom sheet where a MainActivity ViewModel can also do the exact same thing.

What I meant, in order to avoid complexity I use one view model per activity. Now, whenever I want to execute something in fragment or bottom sheet I just pass the view model in the constructor itself. Many people will think this is bad practice but it's not coz as per the concept of view model it will only be created and destroyed in accordance with the activity's lifecycle and only one instance will be created all along. Also by doing this, I can use Dependency injection with the fragment (I don't think that DI works with navigation component but I think you got my point).

Interplay answered 29/4, 2020 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.