Lilly
12/30/2020, 2:08 AMViewModel
...Bradleycorn
12/30/2020, 2:33 AMdata class HomeScreenState(
val loading: Boolean,
val dataValue: DataModel?,
val moreData: MoreModel?
)
class MyViewModel(myRepo: MyRepository): ViewModel {
var homeScreenState by mutableStateOf(HomeScreenState(loading = true, dataValue = null, moreData = null))
private set
init {
viewModelScope.launch {
// This is contrived, but you get the idea
val newData = myRepo.loadSomeData()
homeScreenState = homeScreenState.copy(dataValue = newData)
val moreData = myRepo.loadMoreData()
homeScreenState = homeScreenState.copy(moreData = moreData)
homeScreenState = homeScreenState.copy(loading = false)
}
}
fun onSomeEvent() {
viewModelScope.launch {
homeScreenState = homeScreenState.copy(loading = true)
val newData = myRepo.fetchNewData()
homeScreenState = homeScreenState.copy(loading = false, dataValue = newData)
}
}
}
@Composable
fun HomeScreen(viewModel: MyViewModel) {
val (loading, data, moreData) = viewModel.homeScreenState
if (loading) {
CircularProgressIndicator()
} else {
SomeComposable(visibleData = data, onSomeEvent = { viewModel.onSomeEvent() })
OtherComposable(moreData)
}
}
Shakil Karim
12/30/2020, 7:59 AMmanueldidonna
12/30/2020, 1:13 PMShakil Karim
12/30/2020, 8:26 PMLilly
12/31/2020, 2:53 AMBradleycorn
12/31/2020, 2:58 PMHomeScreen
composable where it calls SomeComposable
... There, it's passing it a lambda for onSomeEvent
... SomeComposable
very well could hook that lambda up to a TextField's onValueChanged
event handler (of course, it would have to be modified a little bit to take a string argument with the new text value), which then would have the effect of calling the viewModel's onSomeEvent
method, where you could store the text (either in memory in the viewmodel, or in a database, or send it off to a network api, etc), and update some State
value that your composables are observing so they can react/recompose with the new value.Lilly
01/04/2021, 8:44 PMmutableStateOf
directly in the viewModel and pass the state to their respective composables. What do you think about that? Like:
SomeComposable(vieModel.state)
I will have ~80 of these composablesBradleycorn
01/04/2021, 10:06 PMclass MyViewModel: ViewModel() {
var state by mutableStateOf(someValue)
private set
fun onSomeEvent() {
state = newValue
}
}
@Composable
fun MyScreen(viewModel: MyViewModel) {
MyChildComposable(viewModel.state)
AnotherChildComposable(viewModel.state, onClick = { viewModel.onSomeEvent() })
}
Bradleycorn
01/04/2021, 10:08 PMLilly
01/04/2021, 10:53 PM