Robert Menke
09/11/2020, 2:46 PMviewModel
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
09/11/2020, 3:20 PMRobert Menke
09/11/2020, 5:06 PMAsh
09/11/2020, 5:31 PM@Preview
@Composable
@Preview never works when I use a viewModel in the @Composable ... R U guys having the same problem? Or it just me?Sourabh Rawat
09/12/2020, 2:06 PMAsh
09/12/2020, 3:09 PM