Home > Software engineering >  how to use observed livedata outside of observe block
how to use observed livedata outside of observe block

Time:11-21

I want to put the observed LiveData in a list and you that list elsewhere in the code. Like this:

        var listCategory = listOf<Category>()

        categoryViewModel.categories.observe(viewLifecycleOwner) {
            listCategory = it
        }
        
        //do something with listCategory

CategoryViewModel.kt

@HiltViewModel
class CategoryViewModel @Inject constructor(private val categoryDao: CategoryDao) :ViewModel() {
    private val categoryFlow = categoryDao.getCategoryFlow()
    val categories = categoryFlow.asLiveData()

    fun addCategory(name:String){
        viewModelScope.launch {
            categoryDao.insert(Category(name = name))
        }
    }
}

CategoryDao.kt

@Dao
interface CategoryDao {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(category: Category)

    @Update
    suspend fun update(category: Category)

    @Delete
    suspend fun delete(category: Category)

    @Query("SELECT * FROM category_table")
    fun getCategoryFlow(): Flow<List<Category>>
}

But listCategory is always empty. How can I use observed data outside the observation block?

CodePudding user response:

Your listCategory has List<Category> type, which is immutable. This is also declared as val, which means that you cannot legally use listCategory = something To allow mutations and adding, you should create it as a mutable list like this

val listCategory = mutableListOf<Category>()

And then, in observe block you can

categoryViewModel.categories.observe(viewLifecycleOwner) {
    listCategory.addAll(it)
}

Moreover I suggest to perform manipulations with livedata and its' dependent components in observe block, to make sure, that livedata changes will be processed.

  • Related