Initializing LiveData on ViewModel constructor

Viewed 1197

I am just a beginner in android programming. Recently I am reading about how room database can return live data for automatic updates when changes were made to the database. I am using the viewmodel class instance to hold my Livedata as follows

public class LogVM extends AndroidViewModel{

      MasterDatabase roomDatabase;
      LiveData<List<Log>> logData;

      LogVM(Application application){
           super(application);
           roomDatabase=MasterDatabase.getInstance(application);
           logData=roomDatabase.getLogDao.getAllLogs();

      }

       public LiveData<List<Log>> getLogData() {
       return logData;
    }

 }

The above code actually works fine. But my question is when initializing the logdata in the constructor, aren't we running the database operation on the main thread? But the code compiles and runs without any warning. Can someone explain how?? Sorry if its a silly question. But I am just a beginner!

1 Answers

Room will create the code for you to ensure that when your database code is executed it is scheduled on a background thread. If you look at the generated code you'll find that the DAO classes use an internal class called ComputableLiveData which uses the IOThreadExecutor to perform its work.

There's a brief description of this in the docs. https://developer.android.com/topic/libraries/architecture/livedata

The Room persistence library supports observable queries, which return LiveData objects. Observable queries are written as part of a Database Access Object (DAO).

Room generates all the necessary code to update the LiveData object when a database is updated. The generated code runs the query asynchronously on a background thread when needed. This pattern is useful for keeping the data displayed in a UI in sync with the data stored in a database. You can read more about Room and DAOs in the Room persistent library guide.

Related