I'm having a real strange issue here. I have a ViewModel that has a StateFlow. That ViewModel is recreated in specific circumstances and sets it's StateFlow value to 0.
I also have Compose view that reads value of this StateFlow and displays text according to it.
Then I change that state to 2, for example. And then recreate the whole Compose view and ViewModel.
But, when I recreate the whole view, and the ViewModel, for brief moment, StateFlow keeps it's old state (even though ViewModel is recreated altogether with the View and state is set to 0), and then switches to the new one, which is zero (this only works if you make a change mentioned below).
This can cause tha crash if we have lists that have different amout of items, and we pass them when view is recreated, because then we will read index value that does not exist and our app will crash.
Changing the list ViewModelTwo(mutableListOf("text4")) to the ViewModelTwo(mutableListOf("text4", "text5", "text6")) will stop the crash. But look at the logs, and you'll see what's going on. First it goes to 2, then to 0, which is default.
I have github repo setup for Compose-Jb. You can open it in Android Studio: https://github.com/bnovakovic/composableIssue
Sorry for using android compose tags, but I could not find Compose-JB tag.
And for convinience, here are the code snippets.
Any help is appreciated
Main.kt
#Composable
#Preview
fun App(viewModelOne: ViewModelOne) {
val showComposable by viewModelOne.stateOne.collectAsState()
MaterialTheme {
// Depending on the state we decide to create different ViewModel
val viewModelTwo: ViewModelTwo = when (showComposable) {
0 -> ViewModelTwo(mutableListOf("text1", "text2", "text3"))
1 -> ViewModelTwo(mutableListOf("text4"))
else -> ViewModelTwo(mutableListOf("blah1", "blah2", "blah3"))
}
// New composable is always created with new ViewModelTwo that has default index of 0, yet the app still crashes
TestComposableTwo(viewModelTwo)
Row {
Button(onClick = {
viewModelOne.changeState()
}) {
Text("Click button below, than me")
}
}
}
}
fun main() = application {
Window(onCloseRequest = ::exitApplication) {
val viewModelOne = ViewModelOne();
App(viewModelOne)
}
}
TestComposableView
#Composable
fun TestComposableTwo(viewModelTwo: ViewModelTwo) {
val currentIndex by viewModelTwo.currentListItem.collectAsState()
println("Index is: $currentIndex")
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
) {
// At the point where we recreate this composable view, currentIndex keeps it's old value, and then changes it
// to the new one causing the app to crash since new list does not have index of 1
Text(text = viewModelTwo.stringList[currentIndex])
Button(onClick = {
viewModelTwo.changeIndex()
}) {
Text("Click me before clicking button above")
}
}
}
ViewModel1
class ViewModelOne {
private val viewModelScope = CoroutineScope(Dispatchers.IO)
private val _stateOne = MutableStateFlow(0)
val stateOne = _stateOne.asStateFlow()
fun changeState() {
viewModelScope.launch {
val currentValue = stateOne.value + 1
_stateOne.emit(currentValue)
}
}
}
ViewModel2
class ViewModelTwo(val stringList: List<String>) {
private val viewModelScope = CoroutineScope(Dispatchers.IO)
private val _currentListItem = MutableStateFlow(0)
val currentListItem = _currentListItem.asStateFlow()
fun changeIndex() {
viewModelScope.launch {
_currentListItem.emit(2)
}
}
}
It seems overly complex to make a new ViewModelTwo in the Composable based on a value in the first ViewModel. Try to make your ViewModel take care of the logic and your Composables just show the data.
I would suggest using a single ViewModel with a single MutableStateFlow.
And you don't need the emit or the viewModelScope in this case.
Something like this should work:
class MainViewModel {
private val _state = MutableStateFlow(State(listOf("text1", "text2", "text3"), 0))
val state: StateFlow<State> = _state
fun onChangeStateClick() {
_state.value = State(listOf("text4"), 0) // Or other logic here if needed
}
fun onChangeIndexClick() {
_state.update {
if (it.currentIndex < it.stringList.count() - 1) {
it.copy(currentIndex = it.currentIndex + 1)
} else it.copy(currentIndex = 0)
}
}
data class State(
val stringList: List<String>,
val currentIndex: Int
)
}
#Composable
#Preview
fun App(viewModel: MainViewModel) {
val state by viewModel.state.collectAsState()
MaterialTheme {
TestComposableTwo(
state.stringList[state.currentIndex],
onButtonClick = { viewModel.onChangeIndexClick() }
)
Row {
Button(onClick = {
viewModel.onChangeStateClick()
}) {
Text("Click button below, than me")
}
}
}
}
#Composable
fun TestComposableTwo(text: String, onButtonClick: () -> Unit) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
) {
Text(text = text)
Button(onClick = onButtonClick) {
Text("Click me before clicking button above")
}
}
}
Related
I have a function like:
#Composable
fun LazyElementList(data: Flow<PagingData<Element>>) {
val scrollState = rememberLazyListState()
val elements = data.collectAsLazyPagingItems()
LazyColumn(state = scrollState) {
items(elements) {
DisplayElement(it)
}
}
}
I would like when navigating to another screen and back to maintain the place in the list.
Unexpectedly, the value of scrollState is maintained when visiting child screens. If it wasn't, it should be hoisted, probably into the ViewModel.
In the code in the question scrollState will be reset to the beginning of the list because there are no items in the list on the first composition. You need to wait to display the list until the elements are loaded.
#Composable
fun LazyElementList(data: Flow<PagingData<Element>>) {
val scrollState = rememberLazyListState()
val elements = data.collectAsLazyPagingItems()
if (elements.isLoading) {
DisplayLoadingMessage()
} else {
LazyColumn(state = scrollState) {
items(elements) {
DisplayElement(it)
}
}
}
}
fun LazyPagingItems.isLoading(): Boolean
get() = loadState.refresh is LoadState.Loading
I have a Text composable within a Box:
Box(modifier = Modifier)
) {
Text(text = "BlaBla" )
}
How can show the Box/Text for a few seconds, only?
You can use LaunchedEffect and delay with a boolean flag and set it false after time specified
#Composable
private fun TimedLayout() {
var show by remember { mutableStateOf(true) }
LaunchedEffect(key1 = Unit){
delay(5000)
show = false
}
Column(modifier=Modifier.fillMaxSize()) {
Text("Box showing: $show")
if(show){
Box{
Text(text = "BlaBla" )
}
}
}
}
There are tons of way you can achieve this, for instance:
You can use AnimatedVisibility in case you want to choose which animation you want.
Example:
AnimatedVisibility(visible = yourFlag) {
Box{
Text(text = "BlaBla")
}
}
If you are using a ViewModel or any pattern and you can observe you can create two states and then inside of the ViewModel / Presenter / Whatever you start the timer you want (doing this you can test it):
sealed class TextState {
object Visible: TextState()
object Invisible: TextState()
}
And then inside the #Composable you do this
val state by presenter.uiState.collectAsState()
when (val newState = state) {
Visible -> {}
Invisible -> {}
}
You can change it also playing with the Alpha
Modifier.alpha(if(isVisible) 1f else 0f)
Another valid option is what #Thracian commented, using Side-Effects
for example :
#Composable
fun YourComposable() {
LaunchedEffect(key1 = Unit, block = {
try {
initTimer(SECONDS_HERE) {
//Timer has passed so you can show or hide
}
} catch(e: Exception) {
//Something wrong happened with the timer
}
})
}
suspend fun initTimer(time: Long, onEnd: () -> Unit) {
delay(timeMillis = time)
onEnd()
}
I have a composable function for the home screen, whenever I navigate to a new composable and come back to this function everything is re created. Do I have to move the view model somewhere higher?
home screen
#Composable
fun HomeScreen(viewModel: NFTViewModel = viewModel()) {
val feedState by viewModel.nftResponse.observeAsState()
if (feedState?.status == Result.Status.SUCCESS) {
val nfts = feedState?.data?.content
LazyColumn {
itemsIndexed(nfts!!) { index, item ->
Card(
modifier = Modifier
.fillMaxWidth()
.padding(15.dp)
.clickable { },
elevation = 8.dp
) {
Column(
modifier = Modifier.padding(15.dp)
) {
Image(
painter = rememberAsyncImagePainter(
item.firebaseUri
),
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = Modifier.height(250.dp)
)
Text(
buildAnnotatedString {
append("Contract Address: ")
withStyle(
style = SpanStyle(fontWeight = FontWeight.W900, color = Color(0xFF4552B8))
) {
append(item.contractAddress)
}
}
)
Text(
buildAnnotatedString {
append("Chain: ")
withStyle(style = SpanStyle(fontWeight = FontWeight.W900)) {
append(item.chain.displayName)
}
append("")
}
)
Text(
buildAnnotatedString {
append("Price: ")
withStyle(style = SpanStyle(fontWeight = FontWeight.W900)) {
append(item.price)
}
append("")
}
)
}
}
}
}
} else {
Column(
modifier = Modifier
.fillMaxSize()
.background(colorResource(id = R.color.white))
.wrapContentSize(Alignment.Center)
) {
Text(
text = "Feed",
fontWeight = FontWeight.Bold,
color = Color.DarkGray,
modifier = Modifier.align(Alignment.CenterHorizontally),
textAlign = TextAlign.Center,
fontSize = 25.sp
)
}
}
}
Navigation
#Composable
fun Navigation(navController: NavHostController) {
NavHost(navController, startDestination = NavigationItem.Home.route) {
composable(NavigationItem.Home.route) {
val vm: NFTViewModel = viewModel()
HomeScreen(vm)
}
composable(NavigationItem.Add.route) {
AddScreen()
}
composable(NavigationItem.Wallets.route) {
WalletsScreen()
}
composable(NavigationItem.Popular.route) {
PopularScreen()
}
composable(NavigationItem.Profile.route) {
ProfileScreen()
}
}
}
It seems like I need to save the view model as a state or something? I seem to be missing something. Basically I dont want to trigger getFeed() everytime the composable function is called, where do I save the data in the compose function, in the view model?
EDIT now calling getFeed from init in the view model
class NFTViewModel : ViewModel() {
private val nftRepository = NFTRepository()
private var successResult: Result<NftResponse>? = null
private var _nftResponse = MutableLiveData<Result<NftResponse>>()
val nftResponse: LiveData<Result<NftResponse>>
get() = _nftResponse
init {
successResult?.let {
_nftResponse.postValue(successResult!!)
} ?: kotlin.run {
getFeed() //this is always called still successResult is always null
}
}
private fun getFeed() {
viewModelScope.launch {
_nftResponse.postValue(Result(Result.Status.LOADING, null, null))
val data = nftRepository.getFeed()
if (data.status == Result.Status.SUCCESS) {
successResult = data
_nftResponse.postValue(Result(Result.Status.SUCCESS, data.data, data.message))
} else {
_nftResponse.postValue(Result(Result.Status.ERROR, null, data.message))
}
}
}
override fun onCleared() {
Timber.tag(Constants.TIMBER).d("onCleared")
super.onCleared()
}
}
However it still seems like a new view model is being created.
It seems like I need to save the view model as a state or something?
You don't have to. ViewModels are already preserved as part of their owner scope. The same ViewModel instance will be returned to you if you retrieve the ViewModels correctly.
I seem to be missing something.
You are initializing a new instance of your NFTViewModel every time the navigation composable recomposes (gets called) instead of retrieving the NFTViewModel from its ViewModelStoreOwner.
You should retrieve ViewModels by calling viewModel() or if you are using Hilt and #HiltViewModel then call hiltViewModel() instead.
No Hilt
val vm: NFTViewModel = viewModel()
Returns an existing ViewModel or creates a new one in the given owner (usually, a fragment or an activity), defaulting to the owner provided by LocalViewModelStoreOwner.
The created ViewModel is associated with the given viewModelStoreOwner and will be retained as long as the owner is alive (e.g. if it is an activity, until it is finished or process is killed).
If using Hilt (i.e. your ViewModel has the #HiltViewModel annotation)
val vm: NFTViewModel = hiltViewModel()
Returns an existing #HiltViewModel-annotated ViewModel or creates a new one scoped to the current navigation graph present on the NavController back stack.
If no navigation graph is currently present then the current scope will be used, usually, a fragment or an activity.
The above will preserve your view model state, however you are still resetting the state inside your composable if your composable exits the composition and then re-enters it at a later time, which happens every time you navigate to a different screen (to a different "screen" composable, if it is just a dialog then the previous composable won't leave the composition, because it will be still displayed in the background).
Due to this part of the code
#Composable
fun HomeScreen(viewModel: NFTViewModel) {
val feedState by viewModel.nftResponse.observeAsState()
// this resets to false when HomeScreen leaves and later
// re-enters the composition
val fetched = remember { mutableStateOf(false) }
if (!fetched.value) {
fetched.value = true
viewModel.getFeed()
}
fetched will always be false when you navigate to (and back to) HomeScreen and thus getFeed() will be called.
If you don't want to call getFeed() when you navigate back to HomeScreen you have to store the fetched value somewhere else, probably inside your NFTViewModel and only reset it to false when you want that getFeed() is called again.
I'm using a Composable which take a content #Composable in parameter, and it seems that with the final version of ConstraintLayout, there is no update.
Here is the code
#Composable
fun Example(
modifier : Modifier = Modifier,
content : #Composable () -> Unit
) {
ConstraintLayout(modifier = modifier
.fillMaxSize()
.background(color = Color.Blue)
) {
val (title, someContent) = createRefs()
Text(text = "a text", modifier = Modifier.constrainAs(title) {
top.linkTo(parent.top)
height = Dimension.wrapContent
width = Dimension.wrapContent
})
Box(modifier = Modifier
.constrainAs(someContent) {
width = Dimension.fillToConstraints
linkTo(start = parent.start, end = parent.end)
linkTo(top = parent.top, bottom = parent.bottom, bias = 1.0f)
height = Dimension.preferredWrapContent
}
.background(color = Color.Yellow)) {
content()
}
}
}
The Box height is initialized with the fist element received by the composable and does not change anymore.
For example, I send to this composable a Column with [Button + result of a Webservice]. The button is displayed at startup, and then after some times I received the result of the API, it does not recompose correctly, the size of the Box stays wrapcontent with the button only!
Am I doing something wrong ?
Moreover, it seems that the behaviour in a compose MotionLayout is the same (no update)
A recomposition only occurs on a composable when at least one of the parameter values change. Because you are set the content parameter to a function, the parameter never changes.
The content parameter is pointing to a function reference and that reference never changes during recomposition.
If you want your composable to recompose with the updated data, you need to add a mutable state variable inside your composable that your viewmodel updates, or pass in a parameter that will change when you have received new data.
Here's an example of updating a parameter value using a state variable in a view model. Updating the state variable recomposes your composable and provides it with the updated variable (name):
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity(intent)
setContent {
val vm: MyViewModel = viewModel()
vm.loadData()
Example(name = vm.name.value) { name ->
Text("Name: $name")
}
}
}
}
class MyViewModel: ViewModel() {
val name = mutableStateOf("")
fun loadData() {
viewModelScope.launch {
delay(2000)
name.value = "Joe Cool"
}
}
}
#Composable
fun Example(
modifier : Modifier = Modifier,
name: String,
content : #Composable (name: String) -> Unit
) {
ConstraintLayout(modifier = modifier
.fillMaxSize()
.background(color = Color.Blue)
) {
val (title, someContent) = createRefs()
Text(text = "a text", modifier = Modifier.constrainAs(title) {
top.linkTo(parent.top)
height = Dimension.wrapContent
width = Dimension.wrapContent
})
Box(modifier = Modifier
.constrainAs(someContent) {
width = Dimension.fillToConstraints
linkTo(start = parent.start, end = parent.end)
linkTo(top = parent.top, bottom = parent.bottom, bias = 1.0f)
height = Dimension.preferredWrapContent
}
.background(color = Color.Yellow)) {
content(name)
}
}
}
I know its not possible to call composable functions inside onClick.
#Composable invocations can only happen from the context of a #Composable function
Compose version - alpha06
But I'm stuck with the below requirement.
The requirement is,
Call a server api call inside an onClick.
LazyColumnFor(items = list) { reports ->
Box(Modifier.clickable(
onClick = {
//API call
val liveDataReportsDetails =
viewModel.getReportDetails("xxxx")
LiveDataComponentForReportsDetails(liveDataReportsDetails)
}
)) {
ReportListItem(
item = reports
)
}
}
So you're right, composable functions cannot be called from within onClicks from either a button or a modifier. So you need to create a value like:
private val showDialog = mutableStateOf(false)
When set to true you want to invoke the composable code, like:
if(showDialog.value) {
alert()
}
Alert being something like:
#Composable
fun alert() {
AlertDialog(
title = {
Text(text = "Test")
},
text = {
Text("Test")
},
onDismissRequest = {
},
buttons = {
Button(onClick = { showDialog.value = false }) {
Text("test")
}
}
)
}
Now finish with changing the boolean where intended, like:
Box(Modifier.clickable(
onClick = {
showDialog.value = true
}
))
I hope this explanation helps, of course the value doesn't have to be a boolean, but you get the concept :).