简体   繁体   中英

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:

    @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

  • get all the CubeCoordinate objects by calling the getCoordinates method which in fact returns an Observable
  • transform the CubeCoordinate objects into Hexagon objects and return the result as a new 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 ? onError is not needed in my case. 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 :

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 . You can make an abstract class that extends Subscriber and implement onError there and leave the other two methods abstract.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM