I have Json Data through which i m doing this .
fun getFact(context: Context) = viewModelScope.launch{
try {
val format = Json {
ignoreUnknownKeys = true
prettyPrint = true
isLenient = true
}
val factJson = context.assets.open("Facts.json").bufferedReader().use {
it.readText()
}
val factList = format.decodeFromString<List<FootballFact>>(factJson)
_uiState.value = ViewState.Success(factList)
} catch (e: Exception) {
_uiState.value = ViewState.Error(exception = e)
}
}
This is the way i m getting my job from viewModle in Ui sceeen
viewModel.getFact(context)
when (val result =
viewModel.uiState.collectAsState().value) {
is ViewState.Error -> {
Toast.makeText(
context,
"Error ${result.exception}",
Toast.LENGTH_SHORT
).show()
}
is ViewState.Success -> {
val factsLists = mutableStateOf(result.fact)
val randomFact = factsLists.value[0]
FactCard(quote = randomFact.toString()) {
factsLists.value.shuffled()
}
}
}
I have fact card where i want to show that fact .also i have there a lambda for click where i want my factList to refresh every time wheneever is clicked.
@Composable
fun FactCard(quote: String , onClick : ()-> Unit) {
val fact = remember { mutableStateOf(quote)}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.
.clickable { onClick() }
) {
Text(.. )
}
}
I dont know how to approch this, i think there is silly thing im doing.
CodePudding user response:
factsLists.shuffled()
returns a new list with the elements of this list randomly shuffled.
CodePudding user response:
Composables can only recompose when you update state data. You aren't doing that. Your click event should return the new quote that you want to display. You then set fact.value
to the new quote. Calling fact.value
with a new value is what triggers a recompose:
when (val result = viewModel.uiState.collectAsState().value) {
is ViewState.Error -> {
Toast.makeText(
context,
"Error ${result.exception}",
Toast.LENGTH_SHORT
).show()
}
is ViewState.Success -> {
val factsLists = mutableStateOf(result.fact)
val randomFact = factsLists.value[0]
FactCard(quote = randomFact.toString()) {
return factsLists.value.shuffled()[0]
}
}
}
@Composable
fun FactCard(quote: String , onClick : ()-> String) {
var fact = remember { mutableStateOf(quote)}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.
.clickable {
fact.value = onClick()
}
) {
Text(.. )
}
}