将RxJava与Paho MQTT一起使用

时间:2018-06-06 15:54:32

标签: android mqtt rx-java2 paho

在我的Android应用程序中,我有一个服务,它有一个类的实例(称之为MQTTClient),它发布或订阅MQTT服务器。我想在Eclipse Paho Android中使用RxJava来管理MQTT订阅和发布操作。

我使用Single可观察和SingleObserver进行发布,Flowable可观察和Observer进行订阅。但我陷入了一个无法弄清楚何时以及如何处置Disposable的地步。

以下是Single

publish方法的MQTTClient Observable
Single<IMqttToken> pubTokenSingle = Single.create(new SingleOnSubscribe<IMqttToken>() {
  @Override
  public void subscribe(final SingleEmitter<IMqttToken> emitter) throws Exception {
    final IMqttToken token = client.publish(topic, mqttMessage);
      token.setActionCallback(new IMqttActionListener() {
        @Override
        public void onSuccess(IMqttToken asyncActionToken) {
            emitter.onSuccess(token);
        }

        @Override
        public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
            boolean hasNetwork = isOnline(context);
          if (hasNetwork && Objects.equals(((MqttException) exception).getReasonCode(),
              MqttException.REASON_CODE_CLIENT_NOT_CONNECTED)) {
            //connect client and retry MQTT pub
            try {
              //connect() is a method in MQTTClient
              //connect() method also utilizes RxJava2 Single.
              //Same issue of disposing a `Disposable` exists in that method as well 
              connect();
              //call the publish method again
            } catch (MqttException e) {
              e.printStackTrace();
              emitter.onError(e);
            }
          } else if (!hasNetwork) {
            emitter.onError(exception);
          } else {
            emitter.onError(exception);
          }
        }
    });
  }
});

以下是SingleObserver

final Disposable[] disposable = new Disposable[1];
SingleObserver<IMqttToken> pubTokenSingleObserver = new SingleObserver<IMqttToken>() {
  @Override
  public void onSubscribe(Disposable d) {
    disposable[0] = d;
  }

  @Override
  public void onSuccess(IMqttToken iMqttToken) {
    //disposable[0].dispose();
    //Planning to use the above as last resort
    //Also thought of moving this to doOnSuccess
  }

  @Override
  public void onError(Throwable e) {
    //Put topic name, and mqtt message in SQLite

    //disposable[0].dispose();
    //Planning to use the above as last resort
    //Also thought of moving this to doOnError
  }
};

有人建议我在相关类中有一个清理方法,在调用onStop时调用它。

我担心在使用disposable.dispose()并且网络操作仍在进行中会发生什么。

如果操作不完整,我如何确保SQLite数据库中至少有详细信息? 我希望解决方案也可以轻松扩展以进行订阅。如果没有,请告诉我可能存在的陷阱。

这是一个学习项目,我正在学习RxJava2,这就是为什么我没有选择RxMQTT。

0 个答案:

没有答案
相关问题