In earlier Android view system, we used to remove any view from the hierarchy calling the removeView API. This was also removing all the memory related and was supposed to be marked for Garbage Collector for the memory to be free.
Now, that after shifting to Jetpack compose, I'm little confused what is the correct way of removing it from the hierarchy?
Due to it's declarative in nature, if we are invoking any Composable that would be seen on the screen. So, should all the UI elements be conditionally controlled here? Below is one example, how I am doing it currently but it doesn't feel right approach for dynamically removing any composable at run time.
@Composable
fun ExampleScreen (pViewModel : MyViewModel)
{
val show : Boolean by pViewModel.show.collectAsState()
if (show) {
Text (text = "ExampleScreen", fontSize = 16.sp)
}
}
class MyViewModel : ViewModel () {
private val private_show : MutableStateFlow<Boolean> = MutableStateFlow<Boolean>(false)
val show : StateFlow<Boolean> = private_show
}
In earlier Android view system, we used to remove any view from the hierarchy calling the removeView API. This was also removing all the memory related and was supposed to be marked for Garbage Collector for the memory to be free.
Now, that after shifting to Jetpack compose, I'm little confused what is the correct way of removing it from the hierarchy?
Due to it's declarative in nature, if we are invoking any Composable that would be seen on the screen. So, should all the UI elements be conditionally controlled here? Below is one example, how I am doing it currently but it doesn't feel right approach for dynamically removing any composable at run time.
@Composable
fun ExampleScreen (pViewModel : MyViewModel)
{
val show : Boolean by pViewModel.show.collectAsState()
if (show) {
Text (text = "ExampleScreen", fontSize = 16.sp)
}
}
class MyViewModel : ViewModel () {
private val private_show : MutableStateFlow<Boolean> = MutableStateFlow<Boolean>(false)
val show : StateFlow<Boolean> = private_show
}
Share
Improve this question
asked Mar 17 at 8:36
Rohan PandeRohan Pande
3474 silver badges10 bronze badges
1 Answer
Reset to default 2What you have written works well without any issues.
But I recommend using collectAsStateWithLifecycle()
instead of collectAsState()
since the latter is not lifecycle-aware.
For a smoother UI, wrap your composable with AnimatedVisibility
instead of using a simple if
statement.
AnimatedVisibility(show) {
Text (text = "ExampleScreen", fontSize = 16.sp)
}