Mehdi Haghgoo
11/25/2020, 5:19 AMasLiveData()
is not understood.
Unresolved referenceasLiveData
class CostViewModel(private val repository: CostRepository): ViewModel() {
val costs : LiveData<List<Cost>> = repository.costs.asLiveData()
fun addCost(vararg cost: Cost) = viewModelScope.launch{
repository.addCost(*cost)
}
}
class CostViewModelFactory(private val repository: CostRepository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(CostViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return CostViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
My Repo:
import kotlinx.coroutines.flow.Flow
class CostRepository(private val costDao: CostDao){
val costs: Flow<List<Cost>> = costDao.getCosts()
suspend fun addCost(vararg cost: Cost){
costDao.addCost(*cost)
}
suspend fun deleteCosts(vararg cost: Cost){
costDao.deleteCost(*cost)
}
}
My Dao:
@Dao
interface CostDao {
@Query("SELECT * FROM cost")
fun getCosts(): Flow<List<Cost>>
@Insert()
suspend fun addCost(vararg cost: Cost)
@Delete()
fun deleteCost(vararg cost: Cost)
}
Kaustubh Patange
11/25/2020, 6:31 AMimplementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
dependency.