Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change LiveData observable query parameter with room database in android?

I am using live data with room database and my activity observes live data provided from room database.

@Query("SELECT * FROM BUS WHERE BUS_CATEGORY = :busCategory")
LiveData<List<Bus>> getLiveBuses( String busCategory);

ViewModels gets LiveData via Dao(Data Access Object) and activity observes this live data.

Now it works fine. But when busCategory changes i can't modify this live data to get buses for newly selected busCategory.

So how can i observe this same liveData where query parameters is changeable?

like image 219
Bashir Fardoush Avatar asked Oct 09 '19 11:10

Bashir Fardoush


People also ask

How do you indicate that a class represents an entity to store in a room database?

Annotate the class with @Entity . Annotate the class with @Database . Make the class extend RoomEntity and also annotate the class with @Room . The DAO (data access object) is an interface that Room uses to map Kotlin functions to database queries.

How do you observe LiveData in activity?

You usually create an Observer object in a UI controller, such as an activity or fragment. Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes.

What is Dao in room?

When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.

Which library will help you asynchronously manage this data?

The Room library includes integrations with several different frameworks to provide asynchronous query execution.


1 Answers

I suggest you to to use viewModel. I did the query and observe changes using MutableLiveData. First step

val mutableBusCategory: MutableLiveData<String> = MutableLiveData()

Setter for mutablelivedata

fun searchByCategory(param: String) {
    mutableBusCategory.value = param
}

observable to observe the change

val busObservable: LiveData<Bus> = Transformations.switchMap(mutableBusCategory) { param->
    repository.getLiveBuses(param)
}

and final step to observe the live data

 busObservable.observe(this, Observer {
        //your logic for list})

and to trigger mutablelivedata

searchByCategory(//categoryName)
like image 151
Zulqarnain Avatar answered Oct 02 '22 00:10

Zulqarnain