Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clearing sharedViewModel

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?

navigation

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.

like image 926
solaza Avatar asked Jul 10 '19 06:07

solaza


People also ask

What is a Sharedviewmodel?

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.

How do I clear my Android model?

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.

What is AndroidViewModel?

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).

What is ViewModelStore?

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.


1 Answers

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()
like image 90
Hayk Melkonyan Avatar answered Oct 16 '22 19:10

Hayk Melkonyan