'Composable don't clear previous state after object.observeAsState() changed
I'm trying to implement a simple loading CircularProgressIndicator() while another data is being fetch. And when the data is ready, to set the correct compose content.
The code works fine at first, the loading indicator shows, then the data is ready and the Composable set the data on OtherComposeContent(). But the loading indicator CircularProgressIndicator() don't disappear and stay on the same UI has the new data.
I tried different implementation but no success.
val objectReady by objectViewModel.objectReady.observeAsState()
LaunchView(state = objectReady)
@Composable
fun LaunchView(state:Boolean?){
if (state == true){
OtherComposeContent() // New view when data is ready. Works fine
} else {
CircularProgressIndicator() // Loading circle while feetching data - Should dissapear when state is true but no
}
Solution 1:[1]
@AndroidEntryPoint
class EntryPointActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val photosVM: PhotosViewModel by viewModels()
setContent {
RbotTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
if (photosVM.snapshotStateList.isEmpty()) {
LoadingState()
} else
MainContent(photosVM.snapshotStateList)
}
}
}
}
}
@Composable
fun LoadingState(){
Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
CircularProgressIndicator()
Text(text = "Loading...", modifier = Modifier.padding(8.dp))
}
}
@Composable
fun MainContent(photoList: SnapshotStateList<PhotosModel>) {
Column {
LazyColumn(
Modifier.weight(1f),
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 8.dp),
) {
items(
items = photoList,
itemContent = {
BasicCard(it)
})
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wadali |
