I think I can use either ViewModel or remember to persist states, so I can share some states and parameters among functions using the follwoing code.
and I think I use fun remembe function instead of ViewModel sometimes.
What are differents about lifecycle between ViewModel and remember function?
@Composable
fun ScreenHome(
recordSoundViewModel: RecordSoundViewModel = hiltViewModel(),
lineParState: LineParameterState = rememberLineParameterState()
) {
}
@Composable
fun ItemContent(
index:Int,
lineParState: LineParameterState = rememberLineParameterState(),
recordSoundViewModel: RecordSoundViewModel = hiltViewModel()
) {
}
@HiltViewModel
class RecordSoundViewModel @Inject constructor(
private val appContext: Application,
): ViewModel()
{
}
class LineParameterState private constructor() {
var isShowFirstRunPrompt by mutableStateOf(false)
val fontSizeSecondary = 12.sp
companion object {
val instance: LineParameterState by lazy { LineParameterState() }
}
}
@Composable
fun rememberLineParameterState(): LineParameterState {
return rememberSaveable {
LineParameterState.instance
}
}
2
Answers
remember
is intended for UI-related things, like keeping track of the position of a UI element being dragged or what index of a drop-down should be shown as selected. You can theoretically use it to store your data/model, but that would be poor separation of concerns and make it very difficult to unit test either your UI or your model. All of your examples above fit this usage.Conversely, it would also be poor separation of concerns to be storing your UI status in the ViewModel.
ViewModel is not only the more sensible place to store the data/model, but since it is a class you can easily connect to databases and web APIs and do complex logic to populate your State there.
Both ViewModel and
remember
can be scoped to either a Fragment or an Activity.this is a example
if
anything
change,field1
orfield2
will reset to1
because the
remember
function will be forget when leave composablebut ViewModel is not, its lifecycle as long as Activity, or even longer