Nicolai
03/21/2022, 10:06 AMabstract class OnboardingBaseViewModel(
private val postNotificationSchemeUseCase: PostNotificationSchemeUseCase,
private val putUserPropertyUseCase: PutUserPropertyUseCase
) : ViewModel() {
// Data that needs to be shared
val _customOptionItems = MutableLiveData<List<CustomOptionItem>>()
val customOptionItems = _customOptionItems
}
Upon my init function in VM1 I want to access the data already set from VM2 however it's null.
VM2 is created like this:
@HiltViewModel
class RemindersTimeViewModel @Inject constructor(
postNotificationSchemeUseCase: PostNotificationSchemeUseCase,
putUserPropertyUseCase: PutUserPropertyUseCase
) : OnboardingBaseViewModel(postNotificationSchemeUseCase, putUserPropertyUseCase)
{
init{
// this is null - but why?
val data = customOptionsItems.value
}
}
I inject the viewmodels into the fragments with Hilt like so:
private val viewModel: RemindersViewModel by activityViewModels()
Adam Powell
03/21/2022, 1:41 PMcustomOptionItems
, not that all VM1s and VM2s share the same customOptionItems
Patrick Kellison
03/21/2022, 2:27 PM@HiltViewModel
class RemindersTimeViewModel @Inject constructor(
...
provideCustomOptionsItemsUseCase: CustomItemsUseCase
) : OnboardingBaseViewModel(postNotificationSchemeUseCase, putUserPropertyUseCase)
class CustomItemsUseCase(){
...
private val _customOptionItems = MutableLiveData<List<CustomOptionItem>>()
val customOptionItems = _customOptionItems
}
You could then store those CustomOptionItems
as persistent data using Room, or you could provide CustomItemsUseCase
as a @Singleton
so that Dagger only instantiates one CustomItemsUseCase
object that would be shared across any other classes that inject it (like your ViewModels).
Just be aware that there are plenty of pitfalls when using the Singleton patternNicolai
03/21/2022, 2:32 PM