1

I'm trying to convert my view models to use the new livedata builder from live data2.0

In all the examples i've seen when you use this new builder pattern they omit how to set parameters take this view model for example, userId is not defined

class UserViewModel : ViewModel() {

    private val repository = UserRepository()

    val user: LiveData<Response<User>> = liveData {
        val data = repository.getUser(userId) // loadUser is a suspend function.
        emit(data)
    }
}

looks pretty clean on concise, but where do I set the userId its not a function.

before i would expose a function that took a paramater then would update the livedata property.

I was thinking of something like this

class UserViewModel : ViewModel() {

    private val repository = UserRepository()

    var userId : String? = null

    val user: LiveData<Response<User>> = liveData {
        val data = repository.getUser(userId) // loadUser is a suspend function.
        emit(data)
    }
}

and the fragment can set the id, but what if I change the id and want to make another network call?

Brian
  • 4,328
  • 13
  • 58
  • 103

0 Answers0