skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. this is a example

    if (anything) {
        var field1 by remember { mutableStateOf(1) }
        Text(field1.toString(), modifier = Modifier.clickable { field1++ })
    } else {
        var field2 by remember { mutableStateOf(1) }
        Text(field2.toString(), modifier = Modifier.clickable { field2++ })
    }
    

    if anything change, field1 or field2 will reset to 1

    because the remember function will be forget when leave composable

    but ViewModel is not, its lifecycle as long as Activity, or even longer

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search