Retrofit + RxJava中的链接请求 [英] Chaining requests in Retrofit + RxJava
问题描述
我有2个API,我想依次发出请求并将它们的数据存储在SQLite中.
I have 2 APIs that I want to make request to in sequence and store their data in SQLite.
首先,我想向API A
发出请求,并将其数据存储在SQL表a
中.然后向API B
发出请求,并将其数据存储在表b
中,并将某些数据存储在表a_b
中.存储在a_b
中的数据仅来自请求B
.
First I want to make request to API A
and store its data in SQL table a
. Then make request to API B
and store its data in table b
and some data in table a_b
. The data stored in a_b
is from request B
alone.
如何使用RxJava做到这一点.我读过一些关于为此使用flatMap的信息,类似
How can I do this using RxJava. I read somewhere about using flatMap for this, something like this
apiService.A()
// store in DB here? How? maybe use map()?
.flatMap(modelA -> {
// or maybe store modelA in DB here?
return apiService.B().map(modelB -> {
storeInDB()l // store B here ?
return modelB;
});
});
如果我不使用lambda函数,这将看起来像普通的嵌套调用一样丑陋.这是更好的方法吗?
If I wasn't using lambda functions, this would look as ugly as normal nested calls. Is this a better way to do it?
推荐答案
我不认为使用map
运算符是处理诸如存储api调用的结果之类的最佳方法.
I don't think using map
operator is the best way to go with things like storing the result of the api call.
我想做的是将doOnNext
运算符中的那些内容分开.因此,您的示例将如下所示:
What I like to do is to separate those things inside doOnNext
operators. So your example would be something like this:
apiService.A()
.doOnNext(modelA -> db.store(modelA))
.flatMap(modelA -> apiService.B())
.doOnNext(modelB -> db.store(modelB));
(自己添加必要的observeOn
和subscribeOn
,就像您需要它们一样)
(add necessary observeOn
and subscribeOn
yourself, exactly like you need them)
这篇关于Retrofit + RxJava中的链接请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!