0

I noticed that in the compose method this observable could be binded to an activity lifecycle to do the desired unsubscription, the problem is that i am doing this in a service, so i cant use this library, or at least i dont know how to get this service lifecycle and bind the observable to it:

return bleDevice
            .establishConnection(false)
            .takeUntil(disconnectTriggerSubject)
            //.compose(RxLifecycle.bindUntilEvent(MISSINGACTIVITYLIFECYCLE, ActivityEvent.DESTROY))
            .doOnUnsubscribe(this::onDestroy)
            .compose(new ConnectionSharingAdapter());

i am using RxandroidBle to scan numerous devices used as interface of for a sensoring system, all goes fine, i do this in a background service, the problem is when i stop the service i cant unsuscribe to that broadcast, i used the example provided in the repo. (UPDATED)

BetoCuevas
  • 123
  • 8

1 Answers1

1

There are several possibilities to tackle this problem:

  1. Unsubscribe by hand (my favourite)

Assign the Subscription resulting from .subscribe() to a property and then in service onStop() just call:

public void onStop() {
  if (subscription != null) {
    subscription.unsubscribe();
    subscription = null;
  }
}

If you have more than one Subscription to unsubscribe from you could check out what is a SerialSubscription or CompositeSubscription which may be useful.

  1. Use disconnectTriggerSubject

Making the disconnectTriggerSubject to accept any value would make the RxBleDevice.establishConnection() to be unsubscribed so the connection will get closed. The downstream may not be aware that it should also unsubscribe. One could pass a special Throwable to the subject which would be passed down to all subscribers.

Just make sure that the subscribers would treat the Throwable passed differently than other

  1. Implement RxLifecycle callbacks for your Service

Probably most tedious path to take. Especially when you found out that RxLifecycle is not a perfect solution

Dariusz Seweryn
  • 3,212
  • 2
  • 14
  • 21