Не обновляется LiveData

Рейтинг: 0Ответов: 1Опубликовано: 12.04.2023

При попытке вставить новые данные в MutableLiveData:private var _listOfJob = MutableLiveData<List<JobItemWithCustomer>>()

данные не добавляются. Данные вставляю вот так:

_listOfJob.value = repository.getJobListInDateRange(dateStart,dateEnd).value

код функции getJobListInDateRange:

override fun getJobListInDateRange(
    dateStart: Long,
    dateEnd: Long
): LiveData<List<JobItemWithCustomer>> {
    return Transformations.map(dao.getJobListInDateRange(dateStart, dateEnd)){
        mapperJoin.mapListDBToListJobWithCustomer(it)
    }
}

dao:

@Query("SELECT * FROM jobitemdbmodel WHERE dateInMils >= :dateStart AND dateInMils <= :dateEnd")
    fun getJobListInDateRange(dateStart:Long, dateEnd:Long): LiveData<List<JobItemWithCustomerDBModel>>`

При этом если я переменной сразу присваиваю значение полученное из репозитория

private var _listOfJob = repository.getJobListInDateRange(0, 999999999999999999)

то данные приходят.

Подскажите пожалуйста в чем может быть ошибка

Ниже привожу весь код ViewModel, репозитория, dao и ссылка на Github

viewModel:

const val TV_DATE_START = true
const val TV_DATE_END = false

class JobListViewModel(application: Application) : AndroidViewModel(application) {

    private val repository = JobItemRepositoryImpl(application)

    private var _newJob = MutableLiveData<JobItemWithCustomer?>()
    val newJob: LiveData<JobItemWithCustomer?>
        get() = _newJob

    private var _dateStart = MutableLiveData<Long>()
    val dateStart: LiveData<Long>
        get() = _dateStart

    private var _dateEnd = MutableLiveData<Long>()
    val dateEnd: LiveData<Long>
        get() = _dateEnd

    private var currentTextView = TV_DATE_START

    //private var _listOfJob = repository.getJobListInDateRange(0, 999999999999999999)
    private var _listOfJob = MutableLiveData<List<JobItemWithCustomer>>()
    val listOfJob: LiveData<List<JobItemWithCustomer>>
        get() = _listOfJob

    init {
        val currentDate = Calendar.getInstance().timeInMillis
        changeDate(currentDate.getYear(), currentDate.getMonth() - 1, currentDate.getDayOfMonth())
    }

    fun changeDate(year: Int, month: Int, dayOfMonth: Int) {
        val calendar = Calendar.getInstance()
        calendar.set(year, month, dayOfMonth)
        val dateInMils = calendar.timeInMillis
        var dateStart = _dateStart.value?:0
        var dateEnd = _dateEnd.value?:0
        when (currentTextView) {
            TV_DATE_START -> dateStart = dateInMils
            else -> dateEnd = dateInMils
        }
        if (!validateDateRange(dateStart,dateEnd)){
            dateStart = dateInMils
            dateEnd = dateInMils
        }
        _dateStart.value = dateStart
        _dateEnd.value = dateEnd
        _listOfJob.value = repository.getJobListInDateRange(dateStart,dateEnd).value
    }

    fun setCurrentTextView(isDateStart: Boolean) {
        currentTextView = isDateStart
    }

    private fun validateDateRange(dateStart: Long, dateEnd: Long): Boolean {
        return dateStart <= dateEnd
    }

    fun addNewJobItem() {
        val date = Calendar.getInstance().timeInMillis
        val newJob = JobItem(
            0,
            date,
            null
        )
        viewModelScope.launch {
            repository.addJobItem(newJob)
            _newJob.postValue(repository.getLastJobItemWithCustomer())
        }
    }

    fun clearNewJob() {
        _newJob.value = null
    }

}

репозиторий:

class JobItemRepositoryImpl(application: Application): JobRepository {

    private val mapper = JobItemMapper()
    private val mapperJoin = JobItemWithCustomerMapper()
    private val dao = AppDatabase.getInstance(application).jobItemDBModelDao()

    override fun getJobListForCustomer(customerId: Int): LiveData<List<JobItemWithCustomer>> {
        return Transformations.map(dao.getJobListForCustomer(customerId)){
            mapperJoin.mapListDBToListJobWithCustomer(it)
        }
    }

    override fun getJobListInDateRange(
        dateStart: Long,
        dateEnd: Long
    ): LiveData<List<JobItemWithCustomer>> {
        return Transformations.map(dao.getJobListInDateRange(dateStart, dateEnd)){
            mapperJoin.mapListDBToListJobWithCustomer(it)
        }
    }

    override suspend fun getLastJobItemWithCustomer(): JobItemWithCustomer {
        return mapperJoin.mapDBToJobWithCustomer(dao.getLastJobItemWithCustomerDBModel())
    }

    override suspend fun getJobItemWithCustomer(id: Long): JobItemWithCustomer {
        return mapperJoin.mapDBToJobWithCustomer(dao.getJobItem(id))
    }

    override suspend fun addJobItem(jobItem: JobItem) {
        dao.addJobItem(mapper.mapJobItemToDBModel(jobItem))
    }

    override suspend fun editJobItem(jobItem: JobItem) {
        dao.editJobItem(mapper.mapJobItemToDBModel(jobItem))
    }

    override suspend fun deleteJobItem(id: Long) {
        dao.deleteJobItem(id)
    }
}

dao:

@Dao
interface JobItemDBModelDao {

    @Query("SELECT * FROM jobitemdbmodel WHERE customerId = :customerId")
    fun getJobListForCustomer(customerId:Int): LiveData<List<JobItemWithCustomerDBModel>>

    @Query("SELECT * FROM jobitemdbmodel WHERE dateInMils >= :dateStart AND dateInMils <= :dateEnd")
    fun getJobListInDateRange(dateStart:Long, dateEnd:Long): LiveData<List<JobItemWithCustomerDBModel>>

    @Query("SELECT * FROM jobitemdbmodel ORDER BY dateInMils DESC LIMIT 1")
    suspend fun getLastJobItemWithCustomerDBModel():JobItemWithCustomerDBModel

    @Query("SELECT * FROM jobitemdbmodel WHERE id = :id")
    suspend fun getJobItem(id:Long): JobItemWithCustomerDBModel

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun addJobItem(jobItem: JobItemDBModel)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun editJobItem(jobItem: JobItemDBModel)

    @Query("DELETE FROM jobitemdbmodel WHERE id = :id")
    suspend fun deleteJobItem(id:Long)

}

Ответы

▲ 0Принят

Вопрос решился путем использования switchMap

val listOfJob = Transformations.switchMap(_dateRange){ dateRange ->
    repository.getJobListInDateRange(dateRange.dateStart, dateRange.dateEnd)
}

статья по switchMap на medium