Hello everyone, I wanted a solution to a certain p...
# android
a
Hello everyone, I wanted a solution to a certain problem. I am using a query to get the count of items with Room. I am using a suspend function with return an Int and in my repository class a suspend function which returns an int and when it comes to the view model class I don’t know how to get the return value from the suspend function without using runBlocking. I want to update the fragment when the app starts and before I navigate to the fragment.
v
I’m not sure I understand what you mean by updating the fragment before navigating to it but you can try something like this. In your viewmodel you could use a coroutine scope like the
viewModelScope
and call launch
viewModelScope.launch {}
. Inside your launch block, you can call your suspending function which retrieves the integer from your repo and resumes once it gets the value. Then in your viewmodel, you can use livedata to notify the fragment of changes
Copy code
fun doSomething() {
   viewModelScope.launch {
      val myInteger = repository.getMyInteger()
      myLiveData.value = myInteger
   }

}
a
Before I click on the cart fragment I want to know about the number of items in the cart. That is what I meant from updating before navigating. @voben
v
If you want to display a badge count on the cart icon, you could probably do it through the fragment or activity that owns the icon. I’m not exactly sure how your app works, im assuming you add items in the
Home
fragment and view added items in the cart fragment when you click the cart icon. In that case you could use a viewmodel scoped to the activity which contains both fragments to communicate from the home fragment to the activity’s cart icon badge count
👍 1