BratinaRok / BlackboardReviewPrototype

0 stars 1 forks source link

use of ViewModel #2

Open RedJocker opened 1 year ago

RedJocker commented 1 year ago

we can use ViewModel on the target solution as you already started doing, but there are some things you should fix.

Do not instantiate the view model class directly, the instance should be managed by a provider if you instantiate it yourself that won't be happening and you will have problems. There are two ways to get an instance, the most usual is to use the delegate, which will look something like this val viewModel: DiceRollViewModel by viewModels() (example taken from documentation https://developer.android.com/topic/libraries/architecture/viewmodel#implement-viewmodel). The other way is using a Factory. This way is used if you want to inject arguments in the constructor of the view model. You will need to do some code to create the factory and then you will use the delegate together with the factory. You can read more about it here https://developer.android.com/topic/libraries/architecture/viewmodel/viewmodel-factories.

It is a good idea to use coroutines, but you should use viewModelScope because it is lifecycle aware, so you won't have problems if the fragment is destroyed during the execution of a coroutine. You will need some extra dependencies which you can take from here https://developer.android.com/topic/libraries/architecture/coroutines#viewmodelscope

BratinaRok commented 1 year ago

I changed ViewModel to AndroidViewModel and pass the Application as a parameter through AndroidViewModel.