Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET FromEventPattern

I'm new to Reactive Extension and unfortunately we use VB.NET so I'm having some trouble converting C# examples to VB.NET.
I'm trying to create a simple ObservableCollection(of String) and subscribe to it. Anytime a string is added to the collection, I want to write it out to the console.
I'm trying to translate this example to VB.NET and am having trouble.

var x = Observable.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
    handler => (sender, e) => handler(sender, e),
    handler => theList.CollectionChanged += handler,
    handler => theList.CollectionChanged -= handler);
}

I've gotten this far, but can't get it to work, I'm sure it's simple, but I'm a newbie.

Dim changes = Observable.FromEventPattern(Of System.Collections.Specialized.NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs) _
(Function(handler) Function(sender, args) handler(sender, args), _
Function(handler) AddHandler theList.CollectionChanged, AddressOf handler, _
Function(handler) RemoveHandler theList.CollectionChanged, AddressOf handler)

Thanks to @Gideon Engelberth for helping me remove the unneeded AddressOf
This compiled fine:

Dim changes = Observable.FromEventPattern(Of 
              System.Collections.Specialized.NotifyCollectionChangedEventHandler, _
              NotifyCollectionChangedEventArgs) _
              (Function(handler) Sub(sender, args) handler(sender, args), _
              Sub(handler) AddHandler theList.CollectionChanged, handler, _
              Sub(handler) RemoveHandler theList.CollectionChanged, handler)
like image 591
Airn5475 Avatar asked Dec 14 '25 16:12

Airn5475


1 Answers

As per request, I usually do like so:

Dim c As New ObservableCollection(Of String)
Dim obs = Observable.FromEventPattern(Of NotifyCollectionChangedEventHandler, 
                                         NotifyCollectionChangedEventArgs)(
                Sub(h) AddHandler c.CollectionChanged, h,
                Sub(h) RemoveHandler c.CollectionChanged, h)

Since h is already a delegate variable, you do not need the AddressOf operator.

like image 196
Gideon Engelberth Avatar answered Dec 16 '25 20:12

Gideon Engelberth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!