-1

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

  • it is `LiveData` ... you need to observe it to get data after some time (as db's operation is done on different thread and results are not ready right after calling this method) – Selvin Feb 20 '23 at 10:39
  • [Even better duplicate](https://stackoverflow.com/questions/59096435/using-livedata-as-state-inside-jetpack-compose-functions) ... which is google: "livedata in jetpack compose" first SO result – Selvin Feb 20 '23 at 14:00

1 Answers1

0

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

Macksly
  • 141
  • 5