I am using Room in my project and I want to get list from the DB but I get null although anytime I don't use live data, I get the values so I know the data is available in the database.
@Dao
interface AddressDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(address: Address): Long
@Query("SELECT * from address")
fun getAll(): LiveData<MutableList<Address>>
}
@Entity(tableName = "address")
data class Address(
@PrimaryKey(autoGenerate = true)
val id: Long = 0L)
class AddressDbRepository @Inject constructor(
private val addressDao: AddressDao
) {
suspend fun insertAddress(address: Address): Long = addressDao.insert(address = address)
fun getAll(): LiveData<MutableList<Address>> = addressDao.getAll()
}
@HiltViewModel
class AddressViewModel @Inject constructor(
private val addressDbRepository: AddressDbRepository,
@DefaultDispatcher private val defaultDispatcher: CoroutineDispatcher,
): ViewModel() {
private var _events2 = MutableLiveData<MutableList<Address>>()
val events2: LiveData<MutableList<Address>> = _events2
fun getAddress() {
job?.cancel()
val handler = CoroutineExceptionHandler { _, throwable ->
val message = when (throwable) {
is HttpException -> throwable.toErrorMessage()
else -> "An Error Occurred."
}
Log.d(
"PLACE_SEARCH_VIEWMODEL ERROR",
"PLACE_SEARCH_VIEWMODEL RESPONSE ERROR ${throwable.localizedMessage}"
)
Log.d(
"PLACE_SEARCH_VIEWMODEL ERROR",
"PLACE_SEARCH_VIEWMODEL RESPONSE ERROR ${message}"
)
}
job = viewModelScope.launch(handler) {
val resp = withContext(defaultDispatcher) {
addressDbRepository.getAll()
}
_events2.value = resp.value
Log.d("PLACE_ADDY_VIEWMODEL", "PLACE_ADDY_VIEWMODEL RESPONSE ${resp}")
}
}
}
Any help as to how I can get the value would be appreciated.