0

How to observe object which is in ViewModel from View? Eg. I have a Class:

class MyClass {
var variable: Int = 0

fun increment() {
    variable += 1
}

In view model I have an instance of this class - MyClassObject. There is a TextView in Fragment and I want to bind it to the MyClassObject.variable

EDIT.

I made sth like this and it works but I think this isn't the best way to do it.

class GameState
{
    private val _variable = MutableLiveData<Int>()
    val variable: LiveData<Int>
        get() = _variable

    init
    {
        _variable.value = 0
    }

    fun increment()
    {
        _variable.value = _variable.value!!.plus(1)
    }
}

ViewModel:

class GameViewModel : ViewModel()
{

    private val _gameState: GameState = GameState()
    val gameState: GameState
        get() = _gameState


    fun imgClick()
    {
        gameState.increment()
    }
}

View:

       <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="@{gameViewModel.gameState.variable.toString()}" />

       <ImageView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:onClick="@{() -> gameViewModel.imgClick()}"

1 Answers1

0

Do you know LiveData?, You can use LiveData component included in Jetpack that's for observing in diff layers such as Repository or ViewModel to other layers.

ImanX
  • 789
  • 6
  • 23