Search code examples
androidandroid-jetpack-composeandroid-roomandroid-livedataandroid-viewmodel

LiveData return null on Jetpack Compose Android


DAO

@Query("SELECT COUNT(category) FROM todolist_table")
    fun getAllTaskCount() : LiveData<Int>

Repo

 suspend fun getAllTaskCount() : LiveData<Int> {
       return todoDao.getAllTaskCount()
    }

ViewModel

  fun getAllTaskCount(){
         viewModelScope.launch(Dispatchers.IO) {
             repository.getAllTaskCount()
         }
    }

View

  val viewModel = ToDoViewModel(application = LocalContext.current.applicationContext as Application)

  val taskCount = viewModel.getAllTaskCounter()

I want to take count of categories from database but it's returning null


Solution

  • Because it is LiveData, you have to observe it in the View. This works a bit different in Jetpack compose (comparing to Fragments).

    What you could do is to declare a variable in your viewModel which holds a reference to the database like so:

    val tasks = repo.getAllTaskCount()
    

    In your view you can observe the changes and do something with the tasks:

    val tasks = viewModel.tasks.observeAsState()
    

    It might be worth checking this part of the documentation, it goes in more in depth into state and observing it: https://developer.android.com/jetpack/compose/state