Home > Net >  Jetpack Compose viewModel not getting value on method
Jetpack Compose viewModel not getting value on method

Time:06-18

I have a class that has composable functions which is private as well as methods i cant get a value from my view model when accessing it from a normal class method but inside a composable i can access it what can i do?

class Example(){
    private var state: myviewmodel = myviewmodel()

    @Composable
    private fun mycomposable(){
      state.updateSomething()
    }

    fun getSomeValue(){
      //not working
      state.getSomething()
    }
}

here is what i tried

class Example(){
    private var state: myviewmodel = myviewmodel()
    private var holdSomething:String = ""
    
    @Composable
    private fun mycomposable(){
      state.updateSomething()
      holdSomething = state.getSomething()
    }

    fun getSomeValue(){
      //not working
      holdSomething
      }
}

What am i doing Wrong here?

Updated

Here is my viewmodel

class myviewmodel: ViewModel(){
    private val _something: MutableLiveData<String> = MutableLiveData("")
    val something: LiveData<Int> = _something

    fun updateSomething(){
      _something.value = "newvalue"
    }

    fun getSomeValue(): String {
      return something.value? : ""
    }
}

CodePudding user response:

I used the same code as in your ViewModel, but I fixed the compiler error for LiveData<Int> to LiveData<String>. I also changed the empty starting state string to "initial value" for this example.

class myviewmodel: ViewModel(){
    private val _something: MutableLiveData<String> = MutableLiveData("initial value")
    val something: LiveData<String> = _something

    fun updateSomething() {
        _something.value = "new value"
    }

    fun getSomeValue(): String {
        return something.value ?: ""
    }
}

In your Example class code I fixed another compiler warning where the name of the function you call does not match the actual function name. So I changed state.getSomething() to state.getSomeValue() and I added a Log.d call to log the result.

class Example {
    private var state: myviewmodel = myviewmodel()

    @Composable
    fun mycomposable() {
        state.updateSomething()
    }

    fun getSomeValue() {
        val result = state.getSomeValue()
        Log.d("Test", result)
    }
}

If you also want to return the result (the value) then add a return statement and change the return type to String for fun getSomeValue().

Then I made a Composable function/component where I call both functions from your class.

@Composable
fun MyComponent() {
    val example = Example()

    // this logs "initial value"
    example.getSomeValue()

    example.mycomposable()

    // this logs "new value"
    example.getSomeValue()
}

And I get the expected results in the log:

D/Test: initial value
D/Test: new value
  • Related