【问题标题】:How to put an updating variable of a blocking function into asynchronous data stream of ReactiveX如何将阻塞函数的更新变量放入 ReactiveX 的异步数据流中
【发布时间】:2019-01-27 00:19:20
【问题描述】:

我正在尝试发送一个 int 变量,该变量在 for 循环中不断更新。在 for 循环中,数据被发布到一个 observable。由于变量在阻塞调用中递增,我想在我的 reactiveX 订阅方法中获取这个值。注意:我不想将此变量添加到我的异步数据流中(即,不使用 publisher.onNext() 方法发送此值)。

在 for 循环的每次迭代中递增 int 变量并发布到 observable 之后,我在一个对象上调用 wait()。在订阅消费中,我取变量的值,然后 notify() 同一个对象。我收到异常“异步循环中断”

public int var=0;

main(String[] args) {
    for loop {
        variable++;
        publisher.onNext(args[0]);
        //call wait on a thread to make sure current value of 'var' 
        //is picked in the getSubscriber() method
        wait(); 
    }
}

public Subscriber<T> getSubscriber() {
    return new Subscriber<Inference>() {
            @Override public void onCompleted() {}
            @Override public void onError(Throwable e) { 
               e.printStackTrace(); 
            }
            @Override public void onNext(Inference infer) {
                //do something

                sysout(var);
                //call notify on the thread to resume control in for 
                //loop
                notify();
            }
    };
}

【问题讨论】:

    标签: asynchronous observable reactive-programming observer-pattern reactivex


    【解决方案1】:

    只需在synchronized 块中调用wait()notify() 即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      • 2021-05-26
      相关资源
      最近更新 更多