- Set Up Class A: Class A should have an event that it notifies whenever data changes.
- Set Up Class B: Class B should have listeners that respond to the event from class A. You will need to ensure that these listeners are executed before other methods in class B.
- Use a Flag or State Variable: In class B, use a flag or state variable to track whether the listeners have been executed. This can help control when other methods are allowed to run.
How to wait for "notify" to call and execute all listeners in Matlab 2015b?
4 次查看(过去 30 天)
显示 更早的评论
I have two classes: A and B. A notifies data change using "notify". Class B has listeners which handle A.notify.
I want to make sure that all listeners added to all instances of class B are called and executed before I call any other function of B.
0 个评论
回答(1 个)
BhaTTa
2024-8-29
To ensure that all listeners in class B are executed before any other function of B is called, you can use a few strategies to manage the flow of your program. Here’s a structured approach:
tep-by-Step Solution
Example Implementation:
Class A
classdef A < handle
events
DataChanged
end
methods
function notifyChange(obj)
notify(obj, 'DataChanged');
end
end
end
Class B
classdef B < handle
properties (Access = private)
listeners
listenersExecuted = false
end
methods
function obj = B(source)
% Add a listener to the DataChanged event of class A
obj.listeners = addlistener(source, 'DataChanged', @(src, event)obj.handleDataChange(src, event));
end
function handleDataChange(obj, ~, ~)
% Perform actions when data changes
disp('Data changed!');
% Set the flag to true after handling
obj.listenersExecuted = true;
end
function someMethod(obj)
% Check if listeners have been executed before proceeding
if ~obj.listenersExecuted
error('Listeners have not been executed yet.');
end
% Proceed with the method's operations
disp('Executing someMethod...');
end
end
end
Usage Example
% Create an instance of class A
a = A();
% Create an instance of class B with a as the source
b = B(a);
% Notify change in class A
a.notifyChange();
% Call someMethod in class B (this will only succeed if listeners have executed)
b.someMethod();
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!