问题描述
我的大本营API的返回和显示待办事项。下面是我现在在做什么的例子:
I'm working with the Basecamp api to return and display to do lists. Here's a sample of what I'm doing at the moment:
bcxClient
.fetchToDoLists()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<BcxToDoList>>() {
@Override
public void call(List<BcxToDoList> bcxToDoLists) {
for( final BcxToDoList toDoList : bcxToDoLists ) {
bcxClient
.fetchToDos( toDoList.bucket.id )
.subscribeOn( Schedulers.io() )
.observeOn( AndroidSchedulers.mainThread() )
.subscribe( new Action1<List<BcxToDo>>() {
@Override
public void call(List<BcxToDo> bcxToDos) {
for( BcxToDo toDo : bcxToDos ) {
toDoList.toDos.add( toDo );
}
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
}
mLoremTextView.setText(bcxToDoLists.get(0).name);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
fetchToDoLists
和 fetchToDos
是改造Web服务调用返回的 BcxToDoList
和 BcxToDos
观测量。
fetchToDoLists
and fetchToDos
are Retrofit web service calls that return the BcxToDoList
and BcxToDos
Observables.
在通过每个BcxToDoList的订阅 fetchToDoLists
我循环,调用 fetchToDos
键,附上我BcxToDo对象原名单。
In the subscription to fetchToDoLists
I loop through each BcxToDoList, call fetchToDos
and attach my BcxToDo objects to the original list.
正如你所看到的,这是一个有点冗长。我可以分离到这两个语句,使其多一点点的可读性。但是,这不是很接收。是否有不同的方式来做到这一点RxJava并提高其可读性?
As you can see, it's a little verbose. I could just separate this into two statements to make it a little bit more readable. But, that's not very Rx. Is there a different way to do this in RxJava and improve its readability?
我可以使用lambda表达式,使这个小巧,但在这个阶段,我更感兴趣的RxJava什么功能,我可以利用的。
I could use lambdas to make this compact, but at this stage I'm more interested in what features in RxJava I could take advantage of.
推荐答案
您不应该在您的通话RxJava打破枷锁,因此你需要flatMap连锁它们。此外Observable.from(),您可以拆分元素融入到独立的观测值的列表。接下来,你可以用了ToList获得元素放回列表中。这里有一个例子:
You should not "break the chain" in your RxJava calls, hence you will need flatMap to chain them. Also Observable.from() lets you split List of elements into separate Observables. Next, you can use toList to get elements back into list. Here's an example :
bcxClient
.fetchToDoLists()
.flatMap(new Func1<List<BcxToDoList>, Observable<BcxToDoList>>() {
@Override
public Observable<BcxToDoList> call(List<BcxToDoList> bcxToDoLists) {
return Observable.from(bcxToDoLists);
}
})
.flatMap(new Func1<BcxToDoList, Observable<List<BcxToDo>>>() {
@Override
public Observable<List<BcxToDo>> call(BcxToDoList bcxToDoList) {
return bcxClient
.fetchToDos(bcxToDoList.bucket.id);
.map(new Func1<List<BcxToDo>, BcxToDoList>() {
@Override
public BcxToDoList call(List<BcxToDo> bcxToDos) {
bcxToDoList.toDos.addAll(bcxToDos);
return bcxToDoList;
}
});
}
})
.toList()
.subscribe(...);
这篇关于RxJava - 合并多个/不同的Web服务调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!