I am unable to set value to LiveData
variable which is declared as MutableLiveData
. The value i am trying to set is LiveData
returned from repository.
Please find below the classes.
Viewmodel.class
// Variable to hold list of tasks Livedata
private val _tasks=MutableLiveData<List<TaskEntity>>()
val tasks:LiveData<List<TaskEntity>>
get() = _tasks
init{
getTasksFromDb()
}
private fun getTasksFromDb(){
viewModelScope.launch {
try {
_tasks.value=taskRepository.getAllTasks() // Showing error here
}catch(exception:Exception){
Log.d(TAG,"Error " exception.message)
}
}
}
Repository
class TaskRepository (val taskDb: TaskDatabase){
suspend fun insert(taskEntity: TaskEntity)=
taskDb.taskDao.insert(taskEntity)
fun update(taskEntity: TaskEntity)=
taskDb.taskDao.update(taskEntity)
fun delete(taskEntity: TaskEntity)=
taskDb.taskDao.delete(taskEntity)
fun getAllTasks():LiveData<List<TaskEntity>> =
taskDb.taskDao.getAllTasks()
}
DAO
@Dao
interface TaskDao {
@Insert
fun insert(taskEntity: TaskEntity)
@Update
fun update(taskEntity: TaskEntity)
@Delete
fun delete(taskEntity: TaskEntity)
@Query("SELECT * FROM tasks")
fun getAllTasks():LiveData<List<TaskEntity>>
}
Here the declared variable as well as the value I am trying to assign is also LiveData.Still
its giving the error
Type mismatch:
Required : List<Entity>, Found: LiveData<List<Entity>>
Can somebody help me in finding what is the issue here ?
CodePudding user response:
The error is self-explanatory. It expects a List but you are trying to assign a LiveData. So you could for example just get the value from the LiveData like this:
_tasks.value=taskRepository.getAllTasks().value
That should get rid of the error, although I'm not sure if that would be the correct implementation
CodePudding user response:
If working in some background thread, then you can't use setValue. You have to use postValue here with some observer.
liveData.postValue("someNewData")
CodePudding user response:
First the Livedata.value require a type of Livedata Generic
val liveData = MutableLiveData<Boolean>()
val liveDataTemp = MutableLiveData<Boolean>()
liveData.value = true //current
liveData.value = liveDataTemp //error
If I understand currently you want observe alltask in activity or fragment.
The following code could help you.
ViewModel
fun getAllTask():LiveData<List<TaskEntity>>(){
return taskRepository.getAllTasks()
}
Activity or Fragment
viewModel.getAllTask().observer(this){
list -> TODO()
}