retrieve a single value from room entity using viewmodel

59 Views Asked by At

I am trying to implement favoriting feature in my application using room db. I am storing the data from an API call and present it using the ViewModel and MutableLiveData. The problem I going through is that I am unable to retrieve just the isFavorite flag from the entity using the viewModel.

The following is data class of my application

@Entity(
    tableName = "astronomyPictures"
)
data class AstronomyPOD(
    val copyright: String?,
    val date: String,
    val explanation: String,
    val hdurl: String?,
    val media_type: String,
    val service_version: String,
    @PrimaryKey
    val title: String,
    val url: String?,
    val isFavorite: Int? = null //THIS IS ONE ATTRIBUTE I AM TRYING TO RETRIEVE
    
)

When I store the API response in the room db I assign a default value to the isFavorite attribute using the below code:

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(astronomyPOD: AstronomyPOD)

    @Transaction
    suspend fun upsert(astronomyPOD: AstronomyPOD) {
        val pod = astronomyPOD.copy(isFavorite = astronomyPOD.isFavorite ?: 1)
        insert(pod)
    }

The below code tries to retrieve the isFavorite value from the database using the title as it is the primary key.

    @Query("SELECT isFavorite FROM astronomyPictures WHERE title = :title")
    suspend fun getIsFavoriteFromTitle(title: String) : Int

The database currently looks like the following: Database table

I have tried using the MutableLiveData isFav and used .postValue() function as below:

private val _isFav = MutableLiveData<Int>()
    val isFav : LiveData<Int>
        get() = _isFav

isFav.postValue(podRepository.toggleFavorite(astronomyPOD.title, astronomyPOD.isFavorite ?: 0))

This is how I call the repository in the viewmodel

fun getIsFavorite(title: String) = viewModelScope.launch {
        val favorite = podRepository.getIsFavoriteFromTitle(title)
        _isFav.postValue(favorite)
    }

I have tried to log the results but it always displays 0. How can I do this?

0

There are 0 best solutions below