简体   繁体   English

RxJava:从Observable正确返回随机对象

[英]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. 我的任务是在Producer中产生给定数量的随机对象(形状-圆形或正方形),将它们打印到控制台,然后在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. 为了生成随机对象,我在抽象类Shape使用了getShape方法,然后在创建Observable时,我使用defer()每次获取新对象。

For printing objects I tried to use doOnNext : 对于打印对象,我尝试使用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))... 消费者方法通常是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. 问题是defer()可以工作两次-在打印形状以及由Consumer请求形状时,Consumer变成了不同的形状。

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. 编辑:我试图删除.doOnNext(System.out::print)并在将其提供给Producer之前,在getShape()方法中打印对象,但是Consumer仍然变成不同的形状。

How can it be solved? 如何解决? How can I create shapes, print them and give the same shapes to Consumer? 如何创建形状,打印形状并将相同的形状提供给Consumer?

I don't understand, why do you want to use defer. 我不明白,您为什么要使用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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