Viewmodel with Hilt

Asked

Viewed 20 times

-1

I’m making a logic in my app to present the appBar of it just when I need wing to appear or not.

For this I did the following Viewmodel: Stateappviewmodel

@HiltViewModel
class StateAppViewModel @Inject constructor(
) : ViewModel() {

    val components: LiveData<VisualComponents> get() = _components

    private var _components: MutableLiveData<VisualComponents> =
        MutableLiveData<VisualComponents>().also {
            it.value = hasComponents
        }

    var hasComponents: VisualComponents = VisualComponents()
        set(value) {
            field = value
            _components.value = value
        }
}

class VisualComponents(
    val appBar: Boolean = false
) ´´´

Na classe que quero que o appBar aparece, eu faço:
 ```stateAppViewModel.hasComponents = VisualComponents(true)´´´

E na MainActivity verifico:


    controller.addOnDestinationChangedListener { _, destination, _ ->
            title = destination.label
            viewModel.components.observe(this, {
                it?.let { hasComponents ->
                    if (hasComponents.appBar) {
                        supportActionBar?.show()
                    } else {
                        supportActionBar?.hide()
                    }
                }
            })
        }

Acredito que esteja fazendo algo errado, pois o viewModel não é injetado pelo Hilt.
Alguém poderia me ajudar?

1 answer

0

Hilt never injects ViewModels (take a look at https://dagger.dev/hilt/view-model.html for more information). You need to initialize your ViewModel in Mainactivity to be able to use it. I suggest the following code for this:

private val viewModel by viewModels<StateAppViewModel>()

Declare the above variable as the instance variable of your Activity. If Android Studio has not found the method viewModels, include dependency "androidx.fragment:fragment-ktx:1.3.2" in his app/build.gradle.

  • Pasta, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.