[英]What is the best practice for returning results gathered from Observables in an Observable?
I'm using RxJava for my project and I am puzzled a bit with this piece of code: 我正在为我的项目使用RxJava,我对这段代码感到困惑:
@Override
public Observable<Hexagon<T>> getHexagons() {
return Observable.create(new OnSubscribe<Hexagon<T>>() {
@Override
public void call(final Subscriber<? super Hexagon<T>> subscriber) {
hexagonDataStorage.getCoordinates().subscribe(new Subscriber<CubeCoordinate>() {
@Override
public void onCompleted() {
subscriber.onCompleted();
}
@Override
public void onError(final Throwable throwable) {
System.err.println(String.format("Cannot get Hexagons: <%s>", throwable.getMessage()));
}
@Override
public void onNext(final CubeCoordinate cubeCoordinate) {
subscriber.onNext(new HexagonImpl<>(gridData, cubeCoordinate, hexagonDataStorage));
}
});
}
});
}
What I'm basically trying to do here is to 我在这里基本上要做的是
CubeCoordinate
objects by calling the getCoordinates
method which in fact returns an Observable
通过调用getCoordinates
方法获取所有CubeCoordinate
对象,该方法实际上返回一个Observable
CubeCoordinate
objects into Hexagon
objects and return the result as a new Observable
. 将CubeCoordinate
对象转换为Hexagon
对象,并将结果作为新的Observable
返回。 This example is working but it is really tiring on my eyes and also smells. 这个例子很有效但是我的眼睛真的很累,还有气味。 Is there a better way to achieve the same result? 有没有更好的方法来实现相同的结果?
Also is there an implementation of Subscriber
which only makes me override onCompleted
and onNext
? 还有一个Subscriber
的实现,只让我覆盖onCompleted
和onNext
? onError
is not needed in my case. 在我的情况下不需要onError
。 I checked the source code but there is a gazillion of implementations and I can't differentiate based on my criteria. 我检查了源代码,但是有大量的实现,我无法根据我的标准进行区分。
To answer your first question - the operator you are looking for is map
: 要回答您的第一个问题 - 您正在寻找的运营商是map
:
public Observable<Hexagon<T>> getHexagons() {
return hexagonDataStorage.getCoordinates()
.map(cubeCoordinate -> new HexagonImpl<>(gridData, cubeCoordinate, hexagonDataStorage))
}
It does exactly what you want - it transforms each item by applying a function. 它完全符合您的要求 - 它通过应用函数转换每个项目。
To answer your second question - I highly suggest you always override onError
, otherwise, if the RxJava stream encounters an exception, it will throw OnErrorNotImplementedException
. 回答你的第二个问题 - 我强烈建议你总是覆盖onError
,否则,如果RxJava流遇到异常,它将抛出OnErrorNotImplementedException
。 You can make an abstract class that extends Subscriber
and implement onError
there and leave the other two methods abstract. 您可以创建一个扩展Subscriber
的抽象类,并在那里实现onError
,并将其他两个方法保留为抽象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.