Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutableLiveData<Pair<Float, Float>>() -> Val cannot be reassigned

In my ViewModel in Android project:

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData

class MainViewModel(application: Application) : AndroidViewModel(application) {
    private var waitressCallContainerHeights = MutableLiveData<Pair<Int, Int>>()

    fun init() {
           waitressCallContainerHeights.value.first = 200
    }
}

But I get compile error in this line:

       waitressCallContainerHeights.value.first = 200

Val cannot be reassigned

I want to set first and second values in fun init

like image 437
Alexei Avatar asked Jun 07 '26 04:06

Alexei


2 Answers

Although your liveData is mutable, the Pair itself isn't. You need to do: waitressCallContainerHeights.value = Pair(200,300/* for example */)

like image 180
r2rek Avatar answered Jun 10 '26 09:06

r2rek


You can also initialise the variable on the declaration itself with apply, something like this:

private var waitressCallContainerHeights = MutableLiveData<Pair<Int, Int>>().apply { value = Pair(200, 300) }

like image 20
Javier Herrero Avatar answered Jun 10 '26 10:06

Javier Herrero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!