简体   繁体   English

如何在RxJava中创建可观察者和观察者?

[英]How to create an observable and observer in RxJava?

I have a void listen function that listens to server pushed data. 我有一个无效的侦听功能,可以侦听服务器推送的数据。 I need to create an observable and observer so i can work with the data using onNext, onComplete and onError. 我需要创建一个可观察和观察者,以便我可以使用onNext,onComplete和onError处理数据。

You might want to look into using a BehaviourSubject 您可能想研究使用BehaviourSubject

private final BehaviorSubject<YourImmutableDataClass> mServerObservable = BehaviorSubject.create();

private void update(YourImmutableDataClass next) {
    mServerObservable.onNext(next);
}

public Observable<YourImmutableDataClass> observe() {
    return mServerObservable.distinctUntilChanged();
}

This is some crude guesswork below. 下面是一些粗略的猜测。

If you are trying to pipe through as in an indefinite stream, rxjava 1.x is not making it easy with backpressure issues but Rxjava2 has a better Observable.create(..target) where you could likely have your listen() implementation to call the target's onnext/onerror/oncomplete. 如果您尝试以不确定的流方式进行管道传递,则rxjava 1.x不能轻松解决反压问题,但是Rxjava2具有更好的Observable.create(.. target),可以在其中调用listen()实现。目标的onnext / onerror / oncomplete。

Of course, there is much code to add for when the subscriber unsubscribes (if that) so that the listeners can be removed. 当然,当订户退订(如果有)时,要添加很多代码,以便可以删除侦听器。 But that's a start. 但这是一个开始。

Demo of the elements of a possible solution: 可能解决方案元素的演示:

CAREFUL: this is not bulletproof code, the listeners list is not thread-safe. 注意:这不是防弹代码,侦听器列表也不是线程安全的。 I just kept it light for now. 我暂时保持清淡。

package tests.rxjava2;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class TestRxjava2Basics {

    static void p(Object msg) {
        System.out.println(Thread.currentThread().getName()+"]: "+msg);
    }

    static void w(long delay) {
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        List<Consumer<String>> listeners = new ArrayList<>(); //NOT THREADSAFE!!!!!
        Consumer<String> c1 = s -> p("consumer permanent: "+s);
        listeners.add(c1);

        Thread machinegun = new Thread(() -> {
            while(!Thread.interrupted()) {
                listeners.forEach(c -> c.accept(""+System.currentTimeMillis()));
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }, "gun");

        machinegun.start();

//      for(int i=0; i<5; i++) {
//          final int fi = i;
//          Consumer<String> c = s -> p("consumer adapter "+fi+": "+s);
//          listeners.add(c);
//          Thread.sleep(1000);
//          
//          listeners.remove(c);
//          Thread.sleep(1000);
//      }

        //equivalent in RX:
        for(int i=0; i<5; i++) {
            final int fi = i;
            Disposable disp = Observable.create(tgt -> {
                    Consumer<String> c = s -> {
                        p("consumer adapter "+fi+": "+s);
                        tgt.onNext(s);
                    };
                    tgt.setCancellable(() -> {
                        p("cancelling consumer adapter "+fi);
                        listeners.remove(c);
                    });
                    listeners.add(c);
                })
                .doOnNext(s -> p("onnext "+fi+": "+s))
                .subscribe();

            Thread.sleep(1000);

            disp.dispose();
            Thread.sleep(1000);
        }

        machinegun.interrupt();
    }

}

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

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