Search code examples
delphispring4d

How to use a IMultiCastEvent from the spring4d?


I'm try to start usage the collections part of a spring4d. But I cann't subscribe to the collection changing events. Get the error: [DCC Error]: E2008 Incompatible types at:

var
  TestList: TObjectList<TObject>;
begin
  ... List initialization code ...

  TestList.OnNotify.Add(TestHandler);     <--- Error here
end

The OnNotify property of the TObjectList declared as:

property OnNotify: ICollectionNotifyDelegate<T>, where

ICollectionNotifyDelegate<T> = interface(IMulticastEvent<Generics.Collections.TCollectionNotifyEvent<T>>)
end;

i.e. the OnNotify.Add method expects a Generics.Collections.TCollectionNotifyEvent, which declared as:

TCollectionNotifyEvent<T> = procedure(Sender: TObject; const Item: T; 
    Action: TCollectionNotification) of object;

my event handler declared as:

procedure TTestClass.TestHandler(Sender: TObject; const Item: TObject; Action: TCollectionNotification);
begin

end;

I'm confused %) please help )


Solution

  • This was caused by the same type definitions in different units:

    Classes.pas:

    TCollectionNotification = (cnAdded, cnExtracting, cnDeleting);

    Generics.Collections.pas

    TCollectionNotification = (cnAdded, cnRemoved, cnExtracted);

    Actually, Spring.Collections uses the type alias to simplify the uses:

    TCollectionNotification = Generics.Collections.TCollectionNotification;

    You can add Spring.Collections after the Classes in your uses list clause.

    P.S.

    It's recommended to use interfaced version IList<T>.