1

I am new to Android Jetpack compose. All i want to do is to update data in UI when it gets from API. Here is my Composable function:

@Composable
fun getCurrentWeather(lat : Double, long : Double, nc : NavHostController,
                      vm: CurrentConditionsViewModel = hiltViewModel()) {

    vm.getWeather(lat = lat, long = long)
    var check by remember { mutableStateOf("") }
    var text by remember { mutableStateOf("") }
    val state = vm._state.value

        when (state) {
            is Resource.Loading -> {

                CircularProgressIndicator(
                    modifier = Modifier
                        .fillMaxSize()
                        .wrapContentSize(align = Alignment.Center)

                )
                check = "hi"
            }

            is Resource.Success -> {
                for (i in state.data!!.weather) {
                    print("called")
                
                }
                state.data.name.let {
                    text = it.toString()
                }
            }

            is Resource.Error -> {
                Log.d("StateError", state.message.toString())

            }
        }
}

And here is my ViewModel:

@HiltViewModel
class CurrentConditionsViewModel @Inject constructor(private val weatherRepository: WeatherRepositoryImpl) :
    ViewModel() {

    val _state: MutableState<Resource<CurrentConditionsDataModel>?> = mutableStateOf(null)


    fun getWeather(lat : Double, long : Double) {
        viewModelScope.launch {
            weatherRepository.getWeather(latt = lat, longg = long).collect {
                _state.value = it
            }
        }
    }
}

Everything is going fine but the only problem is that Composable function is not getting called state variable is updated in view model. I have tried using other variables too such as check and text, yet Composable is only getting called once.

What am I doing wrong? I there anything I have missed? Thanks in advance.

kinza
  • 535
  • 11
  • 31
  • Are you sure it's not getting updated? It might be getting updated infinitely that's why you are not seeing it updated because you call `vm.getWeather(lat = lat, long = long)` on each recomposition. Log or debug collect function, if it's getting called constantly then put your `vm.getWeather(lat = lat, long = long)` inside LaunchedEffect to call it only once – Thracian Nov 27 '22 at 16:35
  • @Thracian I have checked through logs. getWeather is getting called only once. even if do it in LaunchedEffect still the output is same - Composable not updating :( – kinza Nov 27 '22 at 16:51
  • Are you setting `Resource.Loading`? That's when you see `CircularProgressIndicator`, but it looks like not available in your code. Then when your api call is finished you are not able to see `print("called")` or `Log.d("StateError", state.message.toString())`, right? – Thracian Nov 27 '22 at 16:58

0 Answers0