0

I have a live data that I am observing in my fragment, in which I have to act on the result received from LiveData and update my MutableState which is used in a composable.

I am not able to figure out why the MutableState value is not getting changed.

Here is how I am doing it:

 viewModel.urlLiveData.observe(
    this@MyFragment as LifecycleOwner
  ) {
    val url = if (!it.isNullOrEmpty()) {
      //perform operations on the string received from live data (it)
    } else if (!someVariable.isNullOrEmpty()) {
      someVariable
      } else null

    url?.let { finalUrl ->
      Log.d("LOG_TAG", "url1: ${finalUrl}")
      urlMutableState.value = UrlMutableState(url = finalUrl)
      Log.d("LOG_TAG", "url2: ${urlMutableState?.value?.url}")
      
    }
  }

The logcat shows different URLs for url1 and url2 logs. Ideally, it must be same as I am assigning my MutableState a new value.

Here are the logs:

 D/LOG_TAG: url1: javascript:myCallback( )
 D/LOG_TAG: url2: https://someUrl.com/page1

Here, url2 holds the old value of mutableState instead of the new value.

Ali_Waris
  • 1,944
  • 2
  • 28
  • 46
  • Could you post your ViewModel where you emit this LiveData? – Skizo-ozᴉʞS ツ Sep 28 '22 at 07:25
  • There are many occurrences of it, but we are emitting data like this: urlLiveData.postValue("somevalue") – Ali_Waris Sep 28 '22 at 07:29
  • There's a problem with the thing you are posting, that's why I'd like to see the `viewModel` because theres a problem when parsing something because the first value you get is not an url – Skizo-ozᴉʞS ツ Sep 28 '22 at 10:48
  • @Skizo-ozᴉʞS You want to check the initial value of urlLiveData? Well, that's an empty string – Ali_Waris Sep 28 '22 at 13:43
  • Not the empty but all the flow and where you emit the data, because it's weird you emit 2 different strings – Skizo-ozᴉʞS ツ Sep 28 '22 at 13:44
  • Where did I emit two different strings? My logic is that in case the live data emits an empty string, I need to take the value of url from some another variable. – Ali_Waris Sep 28 '22 at 13:45
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/248411/discussion-between-ali-waris-and-skizo-oziks). – Ali_Waris Sep 28 '22 at 13:47

0 Answers0