简体   繁体   English

如何在房间数据库类中获取或观察实时数据

[英]how to get or observe livedata in room database class

I have created an entity along with corresponding dao.我已经创建了一个实体以及相应的 dao。 In dao class, i have a following method:在 dao 类中,我有以下方法:

@Query("select * from Book")
LiveData<List<Book>> getAll();

I have observed this live data in activities and fragments.我在活动和片段中观察到了这些实时数据。 Now i wanted to get the book list when database opened its connection.现在我想在数据库打开连接时获取书籍列表 I want this operation inside room database class.我想在房间数据库类中进行此操作。 Actually inside onOpen() method.实际上在 onOpen() 方法里面。

public abstract class AppDatabase extends RoomDatabase {
...
    public static synchronized AppDatabase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context.getApplicationContext(),
                    AppDatabase.class, DATABASE_NAME)
                    .fallbackToDestructiveMigration()
                    .addCallback(roomCallback)
                    .build();
        }
        return instance;
    }
...
    private static RoomDatabase.Callback roomCallback = new 
        RoomDatabase.Callback() {
        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            new PopulateDbAsyncTask(instance).execute();
        }

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db) {
            super.onOpen(db);
            // get book list information and do some task
        }
    };
}

I am following the android mvvm architecture pattern.我正在遵循 android mvvm 架构模式。 I have some questions at this point.我现在有一些问题。 Is it possible to get the value or observe the livedata(book) inside onOpen() method?.是否可以在 onOpen() 方法中获取值或观察 livedata(book) ? I know I could do this by writing another method in dao class which doesn't return livedata, but will it be a good practice?我知道我可以通过在 dao 类中编写另一个不返回 livedata 的方法来做到这一点,但这会是一个好习惯吗?

You can get the liveData by calling the dao.getAll().您可以通过调用 dao.getAll() 来获取 liveData。 But in general it's not recommended.但一般不推荐。 You will be getting the liveData from the model.您将从模型中获取 liveData。 Check out this sample for recommended way of handling the data and the use of liveData.查看此示例以了解处理数据和使用 liveData 的推荐方式。 https://github.com/googlesamples/android-architecture-components/tree/master/BasicSample https://github.com/googlesamples/android-architecture-components/tree/master/BasicSample

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM