Question about subscribe and unsubscribe

In the documentation, I see that there was a subscribe method added in v2.2.1 that (I think) subscribes to every event for a device:

void subscribe(DeviceWrapper device, String handlerMethod, Map options = null) (Since 2.2.1)

But I don’t see a corresponding unsubscribe method, that takes a device and a handler method. Is that right or am I overlooking it?

The expected option, based on the method signature (DeviceWrapper, String), would be this:

void unsubscribe(DeviceWrapper device, String attributeName) (Since 2.0.7)

But that is obviously used for a different purpose.

Is it possible to pass null or an empty string for the attribute name?

Did you look here?

Yep, that was the source of the information I provided above.

I think this is because the assumption is that if you're subscribing to the events, you want to do something with them (e.g. pass the event to a handler method to do something). If you're unsubscribing, you're just killing off that subscription so there is nothing to pass to a handler.

My use case is for an activity check, like Device Activity Check or Device Health Status, to track the activity of each device. I’m performing the checks for activity once per day by using getLastActivity(). I thought it would be cool if, once the device was deemed as “inactive”, it would subscribe to every event for the device using:

void subscribe(DeviceWrapper device, String handlerMethod, Map options = null)

and then in the handler, send me a notification that the device is back online and unsubscribe that handler. So the handler would only get called for the very first event and wouldn’t bog down the system when the device was “healthy”.

The app will have more than one device and there are additional subscriptions for certain devices, so I can’t use either the parameterless unsubscribe or the device-specific one:

void unsubscribe(DeviceWrapper device)

In other words, I want to unsubscribe from this particular handler for one particular device, but leave all of the other ones intact.

There are other ways I can implement this (e.g. unsubscribe everything when the device becomes “inactive” and then resubscribe everything whenever it becomes “healthy” again), but I feel this would be the cleanest way to do it, if it’s possible.

Off the cuff, you could just store the 'inactive' in a list. Subscribe your events until the device goes active, then unsub for just the device through your handler and remove it from the list.

Alternatively, you could throw the active devices into a list. Then, your first line in your handler could just say if the event device is in the active list, do nothing. If it's not in the active list, add it.

The event subscription alone will not bog down the system. Setting up your handler to always run a few thousand lines of code might. Either of the above methods would circumvent your concern.

1 Like