RxJava。通过少数来源生成 ViewObject 的正确方法
RxJava. Correct way to generate ViewObject by few sources
我有两个实体 类,它们存储在 SQLite 中:UserEntity
和 SessionInfoEntity
:
public class UserEntity{
private Long id;
private String userName;
// ....
}
public class SessionInfoEntity{
private Long id;
private Date beginSessionDate;
private Date endSessionDate;
// ....
}
用户可以有多个会话(一对多关系)。
我有一个存储库,它提供了从我的 SQLite 数据库中获取数据(RxJava observables)的必要方法:
public class MyRepository{
public Observable<List<UserEntity>> getAllUsers(){/* ... */}
public Observable<SessionInfoEntity> getLastSessionInfoForUser(Long userId){/* ... */} // returns info of last session for user with id=userId
}
我需要为每个用户生成下一个 ViewObject,使用 MyRepository
的方法和 RxJava:
public class UserViewObject {
private String userName;
private Integer lastSessionDurationInHours;
// ....
}
事实证明,我需要为每个用户调用 getLastSessionInfoForUser()
才能创建 UserViewObject
。
问题:如何正确使用RxJava生成UserViewObject
?
我正在尝试以这种方式开始:
myRepository
.getAllUsers()
.flatMap(lst -> Observable.from(lst))
.flatMap(ve -> getLastSessionInfoForUser(ve.getId())
.map(lse -> /* ????? */) // In this operator I lose access to current user => I can't generate UserViewObject, because I haven't access to ve.getUserName() method
P.S.: 我无法在 MyRepository 中编写方法,这将是 returns 包含全部信息的对象。
P.P.S.: 以后会添加与User实体相关的新方法(如getLastSessionInfoForUser()
方法)。
您可以在最后flatMap
添加地图。这样你就可以访问 ve
.
myRepository
.getAllUsers()
.flatMap(lst -> Observable.from(lst))
.flatMap(ve -> getLastSessionInfoForUser(ve.getId()).map(lse -> /* ... */))
我有两个实体 类,它们存储在 SQLite 中:UserEntity
和 SessionInfoEntity
:
public class UserEntity{
private Long id;
private String userName;
// ....
}
public class SessionInfoEntity{
private Long id;
private Date beginSessionDate;
private Date endSessionDate;
// ....
}
用户可以有多个会话(一对多关系)。
我有一个存储库,它提供了从我的 SQLite 数据库中获取数据(RxJava observables)的必要方法:
public class MyRepository{
public Observable<List<UserEntity>> getAllUsers(){/* ... */}
public Observable<SessionInfoEntity> getLastSessionInfoForUser(Long userId){/* ... */} // returns info of last session for user with id=userId
}
我需要为每个用户生成下一个 ViewObject,使用 MyRepository
的方法和 RxJava:
public class UserViewObject {
private String userName;
private Integer lastSessionDurationInHours;
// ....
}
事实证明,我需要为每个用户调用 getLastSessionInfoForUser()
才能创建 UserViewObject
。
问题:如何正确使用RxJava生成UserViewObject
?
我正在尝试以这种方式开始:
myRepository
.getAllUsers()
.flatMap(lst -> Observable.from(lst))
.flatMap(ve -> getLastSessionInfoForUser(ve.getId())
.map(lse -> /* ????? */) // In this operator I lose access to current user => I can't generate UserViewObject, because I haven't access to ve.getUserName() method
P.S.: 我无法在 MyRepository 中编写方法,这将是 returns 包含全部信息的对象。
P.P.S.: 以后会添加与User实体相关的新方法(如getLastSessionInfoForUser()
方法)。
您可以在最后flatMap
添加地图。这样你就可以访问 ve
.
myRepository
.getAllUsers()
.flatMap(lst -> Observable.from(lst))
.flatMap(ve -> getLastSessionInfoForUser(ve.getId()).map(lse -> /* ... */))