Jetpack compose - how I can hookup LiveData property from ViewModel with TextField in activity?

35 Views Asked by At

I'd like to display a rationale, where user can be navigated to the settings on accept, or asked for a city name when declined.

I've tried to make there two functions. One, 'displayRationale', and second 'getCityNameFromUser'. When entered to the second function it should display TextField and button. When user will enter anything in TextField, and later on click on button, the value of LiveData property inside of ViewModel should be changed.

I've tried to make it on my own, but it get messy. Here's the code:

ViewModel

@HiltViewModel
class CurrentForecastViewModel @Inject constructor(
    private val repo: repo,
    private val lr: lr
) : ViewModel() {
    private val _cityName = MutableLiveData("")
    val cityName get() = _cityName

    fun onCityNameChange(newCityName: String){
        _cityName.value = newCityName
     }
    }

Activity

  @Composable
private fun displayRationale(
    currentForecastViewModel: CurrentForecastViewModel = viewModel()
) {
    val context = LocalContext.current
    val cityName by currentForecastViewModel.cityName.observeAsState(initial = "")

    AlertDialog(
        onDismissRequest = {},
        confirmButton = { context.startActivity(Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)) },
        dismissButton = {
            Button(onClick = {
                getCityNameFromUser(cityName = cityName) { newCityName ->
                    currentForecastViewModel.onCityNameChange(newCityName)
                }
            }) {
                Text(text = "Enter city instead")
            }
        }
    )
}
@Composable
private fun getCityNameFromUser(cityName: String, onCityNameChange: (String) -> Unit) {
    OutlinedTextField(
        value = cityName,
        onValueChange = onCityNameChange,
        singleLine = true
    )
}
0

There are 0 best solutions below