Retrieving a HashMap LiveData via Room Library

Viewed 1982

I have a social networking app which displays a list of users, and am looking to have an efficient way of being able to retrieve an object from my LiveData using its primary key.

Example: Retrieve a set of User POJOs from within my LiveData<List<User>> given a LIST of userId Integers (ie, users 12, 5, 7, and 1). I need to be able to look up these users by the userId for display in the appropriate order in the UI.

I believe I want something more like LiveData<Map<Integer, User>>, but how could I implement this using the Room database, without breaking the LiveData callbacks from my local DB -> Room -> LiveData -> UI?

PROPOSAL 1:

Change my Room implementation to somehow return a LiveData containing a HashMap of <userId,User>.

Current Room implementation:

@Query("SELECT * FROM users WHERE user_id in :userIds LIMIT 1")
LiveData<List<User>> getUsers(List<Integer> userIds);

Proposed Room implementation (no idea if something like this is possible or what it would even look like):

@Query("SELECT * FROM users WHERE user_id in :userIds LIMIT 1")
LiveData<**HashMap**<Integer,User>> getUsers(List<Integer> userIds);

PROPOSAL 2:

Have a list of many LiveData objects WITHIN a Map:

Map<Integer,LiveData<User>> liveDataUsers;

This might be something to look into, but I'm worried that having potentially hundreds/thousands of LiveData objects within a map is bad design and could also lead to performance issues / too many open LiveData internal callback threads.

PROPOSAL 3:

Something else??? I feel like I am missing something easy here. How are others looking up objects within their LiveData using only their primaryKey?

edit: this is something I'd like to achieve at the Repo / Model level and not at the activity level, as this LiveData will be re-used throughout the app.

0 Answers
Related