我的android应用程序必须使用套接字服务以异步方式处理不同的命令和响应,因为命令需要调用应用程序中的其他组件并等待异步结果。
我尝试使用rxjava将传入的字符串映射到不同的参数,但仍然需要手动路由不同的命令,是否有任何运算符将逻辑路由到自定义的observable并在单个订阅者中处理结果?
代码如下:
template_grid
答案 0 :(得分:2)
我认为您可以使用 groupBy 运算符,因此根据您的cmdResponse,您可以将该observable添加到组中。然后,当可观察完成发射时,您可以检查订户上的组。
此处的官方文档http://reactivex.io/documentation/operators/groupby.html
检查我做的这个例子
/**
* In this example we create a String/Person group.
* The key of the group is just the String value of the sex of the item.
*/
@Test
public void testGroupBySex() {
Observable.just(getPersons())
.flatMap(listOfPersons -> Observable.from(listOfPersons)
.groupBy(person -> person.sex))
.subscribe(booleanPersonGroupedObservable -> {
switch (booleanPersonGroupedObservable.getKey()) {
case "male": {
booleanPersonGroupedObservable.asObservable()
.subscribe(person -> System.out.println("Here the male:" + person.name));
break;
}
case "female": {
booleanPersonGroupedObservable.asObservable()
.subscribe(person -> System.out.println("Here the female:" + person.name));
break;
}
}
});
}
private List<Person> getPersons() {
List<Person> people = new ArrayList<>();
people.add(new Person("Pablo", 34, "male"));
people.add(new Person("Paula", 35, "female"));
return people;
}
您可以在此处查看更多示例https://github.com/politrons/reactive