How to use the TObservable<T>.RemoveListener() in Delphi Spring Framework?

StackOverflow https://stackoverflow.com/questions/16834109

  •  30-05-2022
  •  | 
  •  

Вопрос

In the Delphi Spring framework there is an example on how to use TObservable.AddListener() in the \Spring4D\Samples\SpringDemos\Demo.Patterns\Observer folder.

But there is not an example showing how to use TObservable.RemoveListener().

Here I add a listener FEditorMonitor := TEditorMonitor.Create; FEditorMonitor.AddListener(TCurrentTimeEditUpdater.Create(Edit1));

if I try to use the following code to remome Edit1 from the Listeners, Edit1 continues to be notified:

FEditorMonitor.RemoveListener(TCurrentTimeEditUpdater.Create(Edit1));

any idea?

Это было полезно?

Решение

You should REMOVE the PREVIOUSLY ADDED listener, not create YET ANOTHER NEW listener.

var x: TCurrentTimeEditUpdater;
x := TCurrentTimeEditUpdater.Create(Edit1);

FEditorMonitor.AddListener(x); 

...

FEditorMonitor.RemoveListener(x);
x.Free;
{ optionally } x := nil;

Perhaps your confusion is shown in your idea that you were going "to remome Edit1 from the Listeners". But Edit1 was never and never could be a listener. It just does not have the proper behaviour. What you can add to or remove from listeners collection - is a separate bridging object of some T....Updater class. Not the Edit1 itself.

[Listeners Collections containing(..., Updater1, ...) ] -> [Updater1 for(Edit1)] -> [Edit1]

Your starting code looks to me like

Procedure TMainForm.Button1Click(...);
var NewForm: TMainForm;
begin
    NewForm := TMainForm.Create;
    NewForm.Close;
end;

This would not close the form you already see on the display, more so - it would just leak the memory.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top