Android -room persistent library - DAO calls are async, therefore how to get callback?

后端 未结 3 1952
一向
一向 2021-02-05 05:29

From what i have read Room doesn’t allow you to issue database queries on the main thread (as can cause delays on the main thread)). so imagine i am trying to

3条回答
  •  不思量自难忘°
    2021-02-05 05:58

    There is a way to turn off async and allow synchronous access.

    when building the database you can use :allowMainThreadQueries()

    and for in memory use: Room.inMemoryDatabaseBuilder()

    Although its not recommended. So in the end i can use a in memory database and main thread access if i wanted super fast access. i guess it depends how big my data is and in this case is very small.

    but if you did want to use a callback.... using rxJava here is one i made for a list of countries i wanted to store in a database:

    public Observable queryCountryInfoFor(final String isoCode) {
        return Observable.fromCallable(new Callable() {
            @Override
            public CountryModel call() throws Exception {
                return db.countriesDao().getCountry(isoCode);
            }
        }).subscribeOn(Schedulers.io())
           
     .observeOn(AndroidSchedulers.mainThread());
    

    }

    you can then easily add a subscriber to this function to get the callback with Rxjava.

提交回复
热议问题