如何在Rxjava中取消订阅之前观察套接字

时间:2016-10-09 14:54:07

标签: java rx-java serversocket

我写了一小段代码,它接受一个参数ObjectInputStream并观察套接字上的数据。一旦readObject()函数返回" null"由于函数observeSocket(ObjectInputStream in)只接受Object,订阅者执行onError()函数并终止程序。

但我需要的是继续观察对象的套接字,并且仅当在套接字上观察到对象时才返回,并且仅当观察者取消订阅时该函数才终止其功能。如何修改代码以实现所需的功能。

public Observable<Object> observeSocket(ObjectInputStream in){
    return Observable.create(subscriber -> {
        while(!subscriber.isUnsubscribed()) {
            subscriber.onNext(getData(in));
        }

        subscriber.onCompleted();

    });
}

public Object getData(ObjectInputStream in){

    Object streamData = null;

    try{

        streamData = in.readObject();
    }

    catch(IOException e){
        //e.printStackTrace();
    }

    catch(ClassNotFoundException e){
        e.printStackTrace();
    }

    return streamData;

}

1 个答案:

答案 0 :(得分:2)

避免使用Observable.create(OnSubscribe),因为使背压感知和符合合同的Observables是一项棘手的业务。这是使用Observable.create(SyncOnSubscribe)的理想选择:

ObjectInputStream ois = ...;

Observable<Object> objects = 
  Observable.create(
    SyncOnSubscribe.createStateless(observer -> {
      try {
          Object value = ois.readObject();
          // you decide how end of file is indicated
          // a common strategy is to write a null object
          // to the end of the Object stream.
          if (value == END_OF_FILE) {
              observer.onCompleted();
          } else {
              observer.onNext(value);
          }
      } catch (Exception e) {
          observer.onError(e);
      }
    }));