I am using Delphi CE v11 and TMS.MQTT.Client v 2.0.8.0.
When the client shuts down, multiple memory leaks for TMSMQTTRequestedSubscription objects are reported. I am dynamically subscribing to topics during connection. Here is my code for the subscription process and the close down:
procedure TForm1.ClientConnectedStatusChanged(ASender: TObject; const AConnected: Boolean; AStatus: TTMSMQTTConnectionStatus);
var
i: integer;
begin
if AConnected then begin
for i := low(Topics) to High(Topics) do
MQTTClient.Subscribe(Topics[i]);
end;
end;
...where Topics is an array of strings.
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var
i: integer;
begin
for i := Low(Topics) to High(Topics) do
MQTTClient.UnSubscribe(Topics[i]);
MQTTClient.Disconnect;
sleep(500);
MQTTClient.Free;
end;
Is there a recommended way of handling subscriptions during shutdown?
We can suggest several improvements to your approach
-
Use the TMSMQTTClient.Subscribe overloaded version that has a ATopics: TTMSStringArray parameter to subscribe to many topics with one request.
-
Copy the code in the demos that handle the disconnection. The demos use the TForm.OnCloseQuery to set CanClose to false and call TMSMQTTClient,Disconnect. Then wait for the TMSMQTTClient.OnConnectedStatusChanged event and then check the AConnected argument to close the form safely. Avoid "sleep" calls whenever it's possible.
-
Use the TMSMQTTClient.Unsubscribe overloaded version that has a ATopics: TTMSStringArray parameter to subscribe to many topics with one request but if you used TMSMQTTClient.Connect or TMSMQTTClient.Connect(True) then the broker will remove all subscriptions and other information. In that case it's not necessary to unsubscribe to the topics.