我试图在MVP模式中实现rxandroid,这是我的用例:
一类
List<B> b;
List<B> getB(){
return b;
}
B.class
String dataTochange;
void setDataToChange(String dataToChange){
this.dataToChange = dataToChange
}
我希望在更改B内的值后返回相同的Observable(List(A))。
这就是我所做的,
remote data source.Java:
Observable<List<A>> getAList(){
return FromApiService
.getAList() // returns List<A>
.flatMapIterable(List<A> -> A )
.map(A::getB)
.flatMapIterable(List<B> b -> b)
.map(b -> doSomeDownloading(b))
//After this i want to return the modified
List<A> containing list of B with dataChanged.
}
doSomeDownloading(B b){
somValue = doAsynchronousDownload(b)
b.setDataToChange(somValue);
}
doAsynchronousDownload(B b){
contains callbacks to listeners implemented by View for progress etc;
}
存储库的结构:
PS:执行逻辑是否正确,下载应该在演示者中完成。或者在存储库内!
更新
serviceApi.getAList()
.flatMapIterable(List<A> -> a)
.flatMap(A a ->
Observable.fromIterable(a.getB())
.doOnNext(b ->doSomeDownloading(b))
.toList()
.toObservable()
.map(new Function<List<B>, A>() {
@Override
public A apply(List<B> b) throws Exception
{
a.setB(b);
return a;
}
})
)
.toList()
.toObservable()
.doOnSubscribe(...)
如上所示,doSomeDownloading()的结果被忽略。
这实际上取决于你如何将A转换为List以及如何使用它。如果您的转换很简单(意味着它们不是耗费时间/资源的过程)。您可以使用flatMap来“缓存”您的值ex:
FromApiService.getAList()
.flatMapIterable(List<A> -> A)
.flatMap{a:A ->
Observable.fromIterable(a.getB())
.doOnNext{b -> doSomeDownloading(b)}//or Map/FlatMap if you want
.toList()
.toObservable()//here you have your new list<B>
.map{b -> a.setB(b)}//here you get your A
}