如何在 RxJava 的 onSuccess 案例中做额外的逻辑
How to do additional logic onSuccess case in RxJava
我正在开发 Android 应用程序。
使用了 RxJava。
它将用户数据存储在本地数据库中,并带有过期时间。
首先,它从本地数据库中获取用户数据。
并检查过期时间,如果数据是旧数据,则从远程服务器获取用户数据并更新到本地数据库。
fun getPlayer(playerId: String): Single<Player> {
return playerDao.getPlayer(playerId)
.doOnSuccess { // "doOnSuccess" is right? what method should I use?
if (PlayerUtil.isNeededUpdate(it)) {
Log.d(TAG, "getPlayer(local) - old!")
getPlayerFromRemote(playerId)
// How can I return Observable/Flowable/Single in here?
// (case of need to update data)
}
}
.onErrorResumeNext {
// If local database has no player, then it try to get it from remote server
Log.d(TAG, "getPlayer(local) - onError: ${it.message}")
getPlayerFromRemote(playerId)
}
}
doOnSuccess
旨在用于副作用,而不是影响流本身的操作。
您要找的是 flatMap
如果不需要做任何事情,只需返回标量值:
.flatMap {
if (PlayerUtil.isNeededUpdate(it)) {
getPlayerFromRemote(playerId)
} else {
Single.just(it)
}
}
我正在开发 Android 应用程序。 使用了 RxJava。
它将用户数据存储在本地数据库中,并带有过期时间。
首先,它从本地数据库中获取用户数据。 并检查过期时间,如果数据是旧数据,则从远程服务器获取用户数据并更新到本地数据库。
fun getPlayer(playerId: String): Single<Player> {
return playerDao.getPlayer(playerId)
.doOnSuccess { // "doOnSuccess" is right? what method should I use?
if (PlayerUtil.isNeededUpdate(it)) {
Log.d(TAG, "getPlayer(local) - old!")
getPlayerFromRemote(playerId)
// How can I return Observable/Flowable/Single in here?
// (case of need to update data)
}
}
.onErrorResumeNext {
// If local database has no player, then it try to get it from remote server
Log.d(TAG, "getPlayer(local) - onError: ${it.message}")
getPlayerFromRemote(playerId)
}
}
doOnSuccess
旨在用于副作用,而不是影响流本身的操作。
您要找的是 flatMap
如果不需要做任何事情,只需返回标量值:
.flatMap {
if (PlayerUtil.isNeededUpdate(it)) {
getPlayerFromRemote(playerId)
} else {
Single.just(it)
}
}