简体   繁体   English

RXJava2阅读器可用于并发订阅者

[英]RXJava2 reader Observable with concurrent subscribers

I'm trying to implement an RXJava2 Observable<String> off a BufferedReader . 我正在尝试从BufferedReader实现RXJava2 Observable<String> So far so good: 到现在为止还挺好:

public class Launcher {
    public static void main(String[] args) throws Exception {

        Process process = Runtime.getRuntime().exec("ls /tmp");
        BufferedReader reader = new BufferedReader (new InputStreamReader(process.getInputStream()));

        Observable source = Observable.create(emitter -> {
            String line = "";
            while (line != null) {
                line = reader.readLine();
                if (line == null)
                    break;
                System.out.println("Engine " + Thread.currentThread().getName() + " - " + line); //process line
                emitter.onNext(line);
            }
            emitter.onComplete();
        }).subscribeOn(Schedulers.newThread());

        source.subscribe(line -> System.out.println("UI 1   " + Thread.currentThread().getName() + " - " + line));
        source.subscribe(line -> System.out.println("UI 2   " + Thread.currentThread().getName() + " - " + line));

        TimeUnit.SECONDS.sleep(10);

    }
}

onSubscribe makes subscribers be notified in a parallel fashion. onSubscribe可以并行方式通知订户。 Which, if I'm not mistaken, means that the lambda in create() will be executed in parallel for each consumer. 如果我没记错的话,这意味着create()中的lambda将为每个使用者并行执行。

As a consequence, if I have two subscribers, each of them gets half of the lines of the reader. 结果,如果我有两个订阅者,那么每个订阅者都会获得阅读器行数的一半。 Thread-1 calls readLine() that gets a line Thread-2 will not get, just the next one. 线程1调用readLine()来获得线程2的行,而不会得到下一行。

This all makes sense, still, I must be missing something, because I can't figure out how to: 尽管如此,这一切还是有道理的,因为我不知道如何:

  1. read the lines in one thread 在一个线程中读取行
  2. notify all subscribers concurrently - so each gets all lines 同时通知所有订户-因此每个订户都会获得所有线路

I looked into Subject s, tried to chaining Observable s, still couldn't figure it out yet. 我调查了Subject ,试图将Observable链接起来,但仍无法弄清楚。

Edit: I updated the example to a full runnable class. 编辑:我将示例更新为完整的可运行类。 From what I understand the issue is hot vs cold Observables. 据我了解,问题是可观察到的相对热。 As if the docs said Observable.create(...) should create a cold one, whereas my code clearly behaves as hot. 好像文档说Observable.create(...)应该创建一个冷的,而我的代码显然表现得很热。

Follow-up question: if I add the type parameter making it Observable<String> then the onSubscribe call breaks the code, and it won't compile, as that would return Observable<Object> . 后续问题:如果我添加使其成为Observable<String>的类型参数,则onSubscribe调用将破坏代码,并且它将无法编译,因为这将返回Observable<Object> Why? 为什么? Calling onSubscribe on an intermediate parameter oddly works: 在中间参数上调用onSubscribe很奇怪:

Observable<String> source = Observable.create(emitter -> {...});
Observable<String> source2 = source.subscribeOn(Schedulers.newThread())

Use publish : 使用publish

ConnectableObservable<String> o = Observable.create(emitter -> {
    try (BufferedReader reader = ...) {
        while (!emitter.isDisposed()) {
            String line = reader.readLine();
            if (line == null || line.equals("end")) {
                emitter.onComplete();
                return;          
            }
            emitter.onNext(line);
        }
    }
}).subscribeOn(Schedulers.io())
  .publish();

o.subscribe(/* consumer 1 */);
o.subscribe(/* consumer 2 */);

o.connect();

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

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