BasicRxJavaDemo
数据库设计:
字段名 | 说明 |
---|---|
userid | 用户 id(primarykey) |
username | 用户名字 |
1.Entity
@Entity(tableName = "users")
public class UserEntity {
@PrimaryKey
@ColumnInfo(name = "userid")
private String mId;
@ColumnInfo(name = "username")
private String mUserName;
@Ignore
public UserEntity(String userName) {
mId = UUID.randomUUID().toString();
mUserName = userName;
}
public UserEntity(String id, String userName) {
this.mId = id;
this.mUserName = userName;
}
public String getId() {
return mId;
}
public String getUserName() {
return mUserName;
}
}
2.dao
@Dao
public interface UserDao {
/**
* Get the user from the table. Since, for simplicity we only have one user in the database,
* this query gets all users from the table, but limits the result to just the 1st user.
*
* @return the user from the table
*/
@Query("SELECT * FROM Users LIMIT 1")
Flowable<UserEntity> getUser();
/**
* Insert a user in the database. If the user already exists, replace it.
*
* @param user the user to be inserted.
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertUser(UserEntity user);
/**
* Delete all users.
*/
@Query("DELETE FROM Users")
void deleteAllUsers();
}
3.viewModel
public class UserViewModel extends ViewModel {
private final UserDataSource mDataSource;
private UserEntity mUser;
public UserViewModel(UserDataSource dataSource) {
mDataSource = dataSource;
}
/**
* Get the user name of the user.
*
* @return a {@link Flowable} that will emit every time the user name has been updated.
*/
public Flowable<String> getUserName() {
return mDataSource.getUser()
// for every emission of the user, get the user name
.map(new Function<UserEntity, String>() {
@Override
public String apply(UserEntity user) throws Exception {
return user.getUserName();
}
});
}
/**
* Update the user name.
*
* @param userName the new user name
* @return a {@link Completable} that completes when the user name is updated
*/
public Completable updateUserName(final String userName) {
return new CompletableFromAction(new Action() {
@Override
public void run() throws Exception {
// if there's no use, create a new user.
// if we already have a user, then, since the user object is immutable,
// create a new user, with the id of the previous user and the updated user name.
mUser = mUser == null
? new UserEntity(userName)
: new UserEntity(mUser.getId(), userName);
mDataSource.insertOrUpdateUser(mUser);
}
});
}
}
网友评论