简体   繁体   中英

RxJava: return random objects from Observable correctly

My task is to produce given amount of random object (shapes — circles or squares) in Producer, print them to console and than use them in Consumer. For generating random objects I use method getShape in abstract class Shape and then, while creating of Observable, I use defer() for getting each time new object.

For printing objects I tried to use doOnNext :

Observable<Shape> produceShapes(int amount) {
        System.out.println("Produced following shapes:");
        return Observable.defer(() -> Observable.just(Shape.getShape()))
                .doOnNext(System.out::print)
                .repeat(amount);
    }

Consumer method is usual Observable.just(new Producer().produceShapes(10))...

The problem is that defer() works twice — while printing shapes and while requesting them by Consumer, so Consumer becomes different shapes.

EDIT: I tried to remove .doOnNext(System.out::print) and print the objects in getShape() method, before giving it to Producer, but Consumer still becomes different shapes.

How can it be solved? How can I create shapes, print them and give the same shapes to Consumer?

I don't understand, why do you want to use defer. Defer operator creates new observable for every subscriber. If you just want amount -number of shapes, just try this:

Observable<Shape> produceShapes(int amount) {
    System.out.println("Produced following shapes:");
    return Observable.range(1, amount)
            .map(index -> Shape.getShape())
            .doOnNext(System.out::print);
}

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