https://kotlinlang.org logo
#compose
Title
# compose
r

Robert Menke

09/11/2020, 2:46 PM
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?
Copy code
@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)
    }
}
h

Halil Ozercan

09/11/2020, 3:20 PM
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.
r

Robert Menke

09/11/2020, 5:06 PM
Oh sweet! I’ll definitely check that out and thanks for the heads up!
a

Ash

09/11/2020, 5:31 PM
Copy code
@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

09/12/2020, 2:06 PM
@Ash seems to be working for me.
a

Ash

09/12/2020, 3:09 PM
Great! Now I know and I can fix my issue in confidence that is works :-)
3 Views