How to handle listener lifetime in MATLAB apps?

8 views (last 30 days)
RST
RST on 29 Nov 2023
Answered: RST on 5 Dec 2023
This simple two-window app has a data source app which passes data via an event to one or more listeners. The source is waveformMaker_01.mlapp and receiver(s) xyPlotter_01.mlapp.
Q1) I am principally concerned with the lifetime of the event.listeners.
At present I store these in the receiver and delete them with the receiver's <mainUIFigure>CloseRequest() callback. But the ...CloseRequest() callback is not called when the receiver is simply delete()-ed, which leaves the event.listeners extant but invalid. For now I can call close( <receiver>.<mainUIFigure>) but the principle that destructors must properly close resources when objects go out of scope is broken.
Is there a better way to control the lifetime of the event.listeners?
Q2) There is a choice to either send data in a custom EventData class or to poll the source for the next chunk of data. Which method is preferred? (I recognise that my AnyEventData class is a kludge.)
Q3) Any other code review comments?

Answers (1)

RST
RST on 5 Dec 2023
Answering my own question.
I have not tried MagicListener for this, but it looks useful.
Instead, my client app
  • saves a list of listeners that link to it.
  • listens its ObjectBeingDeleted event, as this is more consistent than the CloseRequest callback
  • deletes the listeners within its ObjectBeingDeletedCallback
as per this code snippet
properties (Access = private)
listenerList (1,:) event.listener
end
methods (Access = public)
.
.
.
function sourceChangedCallback( app, src, evdata )
% do useful things...
end
function addSourceChangedListener( app, src, eventName )
app.listenerList(end+1) = addlistener(src, eventName, @app.sourceChangedCallback);
end
end
methods( Access = private)
function beingDestroyedCallback( app, src, evdata ) %#ok<INUSD>
app.deleteListeners();
end
function deleteListeners( app )
delete( app.listenerList );
app.listenerList = event.listener.empty();
end
end
.
.
.
% Code that executes after component creation
function startupFcn(app)
addlistener(app, 'ObjectBeingDestroyed', ...
@app.beingDestroyedCallback);
end

Categories

Find more on Develop Apps Using App Designer in Help Center and File Exchange

Products


Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!