Assign value from LiveData inside ViewModel

Viewed 144

Is it possible to assign a value from a LiveData from within a ViewModel? I want to assign the value of exercise to dayOfWeek when the ViewModel is initialized however the value is always null:

class UpdateViewModel(
    exerciseKey: Long = 0L,
    dataSource: ExerciseDatabaseDao
    ) : ViewModel() {

        val database = dataSource
        private val exercise: LiveData<Exercise> = database.getExerciseWithId(exerciseKey)

        private val dayOfWeek = MutableLiveData(exercise.value!!.dayOfWeek) //NullPointerException

}

DAO:

@Dao
interface ExerciseDatabaseDao {

    ...

    @Query("SELECT * from exercise_list_table WHERE exerciseId = :key")
    fun getExerciseWithId(key: Long): LiveData<Exercise>
}

From what I understand LiveData isn't initialized until there are observers, is there any way around this?

Thanks.

0 Answers
Related