Robert Menke

    Robert Menke

    2 years ago
    So fwiw I do think I have my dagger hilt + compose example working as expected. I didn’t think that compose’s built in
    viewModel
    function would be compatible with Hilt’s system, which was my main mental hurdle. The following works just fine as far as I know. Are there any caveats to using this approach? Will this work fine for more complex scenarios?
    @AndroidEntryPoint
    class MainActivity: AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContent {
                MyApplicationTheme {
                    // A surface container using the 'background' color from the theme
                    Surface(color = MaterialTheme.colors.background) {
                        Counter()
                    }
                }
            }
        }
    }
    
    @Composable
    fun Counter() {
        val viewModel = viewModel<CounterViewModel>()
        val state by viewModel.counter.observeAsState(0)
    
        Column(
            modifier = Modifier
                .clickable(onClick = viewModel::increment)
                .padding(all = 36.dp)
        ) {
            Text(text = "Counter $state")
        }
    }
    
    @ActivityScoped
    class CounterViewModel @ViewModelInject constructor(): ViewModel() {
        private var _counter: MutableLiveData<Int> = MutableLiveData(1)
        val counter: LiveData<Int> = _counter
    
        fun increment() {
            _counter.value = _counter.value?.plus(1)
        }
    }
    Halil Ozercan

    Halil Ozercan

    2 years ago
    Yes it works because it basically uses the good old ViewModel APIs under the hood anyway. One thing that you might find annoying is that your ViewModelStore will still be provided by the Activity or Fragment. So if you are planning to scope a ViewModel to a specific composable, that's still in the works. In the meantime you can checkout JetNews sample. It has a workaround for the case I have mentioned.
    Robert Menke

    Robert Menke

    2 years ago
    Oh sweet! I’ll definitely check that out and thanks for the heads up!
    Ash

    Ash

    2 years ago
    @Preview
    @Composable
    @Preview never works when I use a viewModel in the @Composable ... R U guys having the same problem? Or it just me?
    s

    Sourabh Rawat

    2 years ago
    @Ash seems to be working for me.
    Ash

    Ash

    2 years ago
    Great! Now I know and I can fix my issue in confidence that is works 😃