我有一个问题,我需要从api(站点)中获取数据,选择其中一个结果(站点ID)并将其传递给另一个api调用(以获取站点详细信息),然后才应该插入值(在Station数据库中)具有所有完整信息。这些是我的方法,它们通过两个api进行感染,并插入Room database
中。
我在棘手的地方发表评论。
这是我的第一种方法
@SuppressLint("CheckResult")
fun fetchAndUpdateDb(onSuccess: (User) -> Unit, onError: (Exception) -> Unit) {
val login = accountUtils.getCurrentAccount()?.name
?: return onError(Exception("No user Account")).also { cleanUserDatabase() }
val password = accountUtils.getPassword()
if (login.contains('@'))
apiManager.loginAndFecthUserData(login, password, { update(it, onSuccess, onError) }, onError)
}
这是我的第二种方法:
fun update(userInfo: UserInfo, onSuccess: (User) -> Unit, onError: (Exception) -> Unit) {
cardsRepository.updateCards(userInfo.AssociatedCards.AssociatedCards.distinctBy { it.number },
{
//To cut code, I receive all the user info here
// I am picking the api user data response and pick the favouriteStation
doAsync {
loadStations(userInfo.generalInfo?.favouriteStation?.toInt()!!)
}
//only after the stations being load I should do this(PURPOSE OF THIS QUESTION)
val entity = UserEntity(
userInfo.generalInfo!!.clientNumber,
userInfo.generalInfo.firstName,
userInfo.generalInfo.lastName,
userInfo.generalInfo.favouriteStation,
userInfo.totalPoints.total,
userInfo.generalInfo.accountState,
stationName
)
userDao.insert(entity)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
onSuccess(entity.toDomain())
},
{ onError(Exception(it.message)) }
)
}, onError
)
}