android-room - 从android Room Architecture Component中的多对多结构中获取LiveData

标签 android-room android-architecture-components android-livedata android-viewmodel android-jetpack

让我们举一个基本的例子

用于存储用户的表

@Entity (tableName="users") 
class UsersEntity(
     @PrimaryKey val id
     var name:String,
      ...
) 

用于存储角色的表
@Entity (tableName="roles") 
class RolesEntity(
     @PrimaryKey val id
     var name:String,
      ...
) 

用于存储用户和角色之间多对多关系的表
@Entity (tableName="roles") 
class UserRoles(
     @PrimaryKey val id
     var userId:String,
     var roleId:String
) 

我的 View 中需要的 pojo 类
class user(
    var id:String,
    var name:String,
     .... other fields
     var roles: List<Role>
)

在我的 ViewModel我怎样才能通过 user结果为 LiveData还有List<Role>填充?

从一般的方式来看,我可以:
  • UserDao.getUserById(id)返回 LiveData来自用户表和 RoleDao.getRolesForUserId(id)返回 LiveData包含用户的角色列表。然后在我的片段中,我可以做 viewModel.getUserById().observe{}viewModel.getRolesForUserId().observe{} .但这基本上意味着有 2 个观察员,我非常有信心这不是要走的路。
  • 可能其他方式是能够在我的存储库或 View 模型中以某种方式混合它们,以便它返回我需要的东西。我去查MediatorLiveData
  • 最佳答案

    使用用户及其角色创建不同的模型,并使用 @Embedded@Relation注释。

    举个例子:

    public class UserModel {
      @Embedded
      UserEntity user;
      @Relation(parentColumn = "id", entityColumn = "userId", entity = UserRoles.class)
      List<UserRoleModel> userRoles;
    }
    
    public class UserRoleModel {
      @Embedded
      UserRoles userRole;
      @Relation(parentColumn = "roleId", entityColumn = "id")
      List<RoleEntity> roles; // Only 1 item, but Room wants it to be a list.
    }
    

    您可以使用 UserModel从这里。

    关于android-room - 从android Room Architecture Component中的多对多结构中获取LiveData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51614101/

    相关文章:

    android - 房间;将整数数组存储到单独的表中?

    android - 在回收器 View 的适配器内的单项 View 中使用 ViewModel 方法好吗?

    android - 我可以使用数据绑定(bind)将 UI 与我的 View 模型中的数据绑定(bind)吗?

    android - Room Persistence @Relation 在 Java 中工作,但在 Kotlin 中不工作

    java - LiveData观察者的onchanged()方法执行多次

    Android MVVM 和 Retrofit api 响应为空

    android - 在 java 中更有效地执行此任务以使用 CSV 插入 Room 数据库的方法

    android - 错误 :Program type already present: android. arch.lifecycle.LiveData

    android-sqlite - 通过从断言复制数据库文件在 Room 中使用预填充的数据库

    android - 带有 LiveData、存储库和 View 模型的房间数据库如何协同工作?