Skip to main content
1-Visitor
June 4, 2018
Solved

How to know if a dynamic subscription alreay exists?

  • June 4, 2018
  • 1 reply
  • 3016 views

Hello, I wrote a service I called SetDynamicSuscriptionToStream in a thing template which generates a dynamic subscription to a stream (MyStream).

MyTemplate : ThingTemplate (<- service SetDynamicSuscriptionToStream() is in here)

MyThing : is a Thing which has MyTemplate as Base Thing Template.

In MyTemplate there is a ThingStart subscription which runs SetDynamicSuscriptionToStream().

Now, my problem is anytime I work on MyTemplate and update it, MyThing is automatically restarted and SetDynamicSuscriptionToStream() is triggered and it tries to create the dynamic subscription again, so I get an error message

There is already a subscription to MyStream for MyThing:Type.Thing:Entity.MyStreamEvent.MyEvent

Is there a way to check if a dynamic subscription exists so that I don't get this error?

Thanks

 

Best answer by CarlesColl

Try/catch on remove, that's the way I do:

 

params = {
 propertyName: subscription.propertyName,
 thingName: subscription.thingName,
 eventName: subscription.eventName,
 serviceName: subscription.serviceName
 };
// -- We ensure not to trigger an error about duplicating a subscription
 // -- Also that's good on the case we are executing this after a dependency
 // -- Restart and becouse of the current Dynamic Subscription it's outdated
try{
 refThing.RemoveDynamicSubscription(params);
 refThing.AddDynamicSubscription(params);
 } catch(err) {
 logger.error("[wupGenericTS("+thingName+")].Init Error re-enabling a dynamic subscription "+JSON.stringify(params)+". ERROR: "+err);
 }

1 reply

14-Alexandrite
June 4, 2018

Good day @fmanniti,

 

I am not sure whether there is a way to get the current subscriptions, I would also like to know if there is a way I am not aware of, but one way you could avoid the error is to put the SetDynamicSuscriptionToStream code body into a try-catch statement (found under flow control in snippets). 

 

The downside to this is you would not pick up an error if something else goes wrong either, but if you are confident in the inputs to create the subscription it should not be a problem.

 

I hope it helps a bit.

 

Kind regards,

Johan Bester

1-Visitor
June 4, 2018

Just remove it first, and then recreate it.

fmanniti1-VisitorAuthor
1-Visitor
June 5, 2018

Actually that's not the solution because when I create it in first place (at "real" thing start), I get the error that you cannot remove a dynamic subscription which doesn't exists