简体   繁体   English

如何在不破坏 MVP 模式的情况下使用 Room?

[英]How to use Room without breaking the MVP pattern?

I'm using a Room database in my app and I'm trying to follow the MVP pattern, so I want to use a presenter to call functions that perform database operations.我在我的应用程序中使用 Room 数据库并且我正在尝试遵循 MVP 模式,所以我想使用演示者来调用执行数据库操作的函数。 An android application Context is needed to get a database reference so in the View (Activity) I call:需要一个 android 应用程序上下文来获取数据库引用,因此在视图(活动)中我调用:

AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "AppDatabase").build();

AppDatabase is an abstract class that extends RoomDatabase , has a bunch of android imports and contains a DAO interface. AppDatabase是一个抽象的 class 扩展RoomDatabase ,有一堆android导入并包含一个DAO接口。 This design is from Android's official guide.这个设计来自Android的官方指南。

Now, would it break the MVP pattern if I passed and used that AppDatabase object (or the DAO interface since it is the one that actually contains database operations methods) in the presenter?现在,如果我在演示者中传递并使用该AppDatabase object(或DAO接口,因为它是实际包含数据库操作方法的接口),它会破坏 MVP 模式吗? The DAO contains SQL queries and has a bunch of android imports, with methods like dao.insert(item) . DAO 包含 SQL 查询,并有一堆 android 导入,使用类似dao.insert(item)的方法。

edit:编辑:

AppDatabase class and ItemDao interface: AppDatabase class 和ItemDao接口:

@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
    public abstract ItemDao itemDao();
}

@Dao
public interface ItemDao {
    @Query("SELECT * FROM item")
    List<Item> getAll();

    @Query("SELECT * FROM item WHERE date BETWEEN :from AND :to")
    List<Item> findItemsBetweenDates(LocalDate from, LocalDate to);

    @Insert
    void insert(Item... items);
}

No you wont be breaking MVP structure as long as dependencies are travelling from the View(Activity or Fragments) to the Presenter.不,只要依赖项从 View(Activity 或 Fragments)传输到 Presenter,您就不会破坏 MVP 结构。 It is a good idea to expose your DAO rather than the app database.公开您的 DAO 而不是应用程序数据库是一个好主意。

I would also suggest to add the AppDatabase class file to your post to make it more explicit.我还建议将AppDatabase class 文件添加到您的帖子中,以使其更加明确。

EDIT编辑

Instead of exposing DAO, create Repository interface, which abstracts DAO and the repository's implementation itself from the calling element(which could be PRESENTER, CONTROLLER or VIEWMODEL, whatever you prefer).与其公开 DAO,不如创建 Repository 接口,该接口从调用元素(可以是 PRESENTER、CONTROLLER 或 VIEWMODEL,无论您喜欢什么)抽象 DAO 和存储库的实现本身。 This will make the Repository only dependent on DAO's public API and not on its implementation, make DAO only dependent on the Entities it uses and make Entities a completely free element.这将使存储库仅依赖于 DAO 的公共 API 而不是其实现,使 DAO 仅依赖于它使用的实体并使实体成为完全免费的元素。

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

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