I am using Koin for injecting viewModel into fragment. My app is single activity. I need that sharedViewModel only in servisFragment and partFragment. I would like to clear that viewModel from Activity after navigation marked with red.
How can I do that?
Code for injecting viewModel
private val servisViewModel by sharedViewModel<ServisViewModel>()
Koin sharedViewModel
inline fun <reified T : ViewModel> Fragment.sharedViewModel(
name: String? = null,
noinline from: ViewModelStoreOwnerDefinition = { activity as
ViewModelStoreOwner },
noinline parameters: ParametersDefinition? = null
) = lazy { getSharedViewModel<T>(name, from, parameters) }
Thank you for any help.
In android, we can use ViewModel to share data between various fragments or activities by sharing the same ViewModel among all the fragments and they can access everything defined in the ViewModel. This is one way to have communication between fragments or activities.
As stated by @Nagy Robi, you could clear the ViewModel by call viewModelStore. clear() . The problem with this is that it will clear ALL the view model scoped within this ViewModelStore . In other words, you won't have control of which ViewModel to clear.
AndroidViewModel. Application context aware ViewModel . ViewModel is a class that is responsible for preparing and managing the data for an Activity or a Fragment . It also handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).
A ViewModelStore can be considered as a container that stores the ViewModels in a HashMap . Where the key is string value and value is the ViewModel being saved( ViewModelProvider uses a concatenation of the string_key + ViewModel class canonical name). A ViewModelStoreOwner is merely an interface.
if you need to clear all viewModels
from that Fragment
try this in your Fragment
viewModelStore.clear()
if you need to clear concrete ViewModel
try this
getViewModelStore(ViewModelParameters(...)).clear()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With