I would generally write your extensions like this:
<Extension()>
Public Function ObserveTextChanged(textbox As TextBox) As IObservable(Of String)
Return Observable _
.FromEventPattern(Of EventArgs)(textbox, "TextChanged") _
.Select(Function(a) textbox.Text) _
.DistinctUntilChanged()
End Function
<Extension()>
Public Function ObserveCheckedChanged(radio As RadioButton) As IObservable(Of Boolean)
Return Observable _
.FromEventPattern(Of ItemCheckedEventArgs)(radio, "CheckedChanged") _
.Select(Function(a) radio.Checked)
End Function
I removed the ControlScheduler
entirely. Now this only because you want to develop a good habit observing on the UI thread at the last possible moment. So, you would use your code like this:
Dim myQuery = MyTextBox _
.ObserveTextChanged() _
.Throttle(TimeSpan.FromSeconds(0.3))
Dim mySubscription = myQuery _
.ObserveOn(Me) _
.Subscribe(Function(text) DoSomethingWith(text))
The reasoning behind this is that many of the Rx operators will implicitly change the observable's scheduler.
For example:
Dim otherQuery = _
From text in MyTextBox.ObserveTextChanged() _
from choices in Observable.Start(Function () GetSpellingChoices(text)) _
select choices
That will automatically change the scheduler that the query uses to Scheduler.Default
. So you would have to add another ObserveOn(control)
to the query if your subscriber is going to update the UI.
So the basic way on thinking about it should be that if your subscriber updates the UI then do an ObserveOn
just before the Subscribe
.
Also, in your extension methods, I removed the DirectCast(a.Sender, TextBox)
code. You don't need it as textbox
is already in scope.
Finally you should be doing something with the IDisposable
returned from the Subscribe
method. You must dispose of the subscription when you close your form otherwise you'll have a lot of event handler wired up preventing garbage collection. I typically create a class-level CompositeDisposable
to hold all my subscriptions so that I can dispose all of my subscriptions in one go.
Hopefully this give you a few pointers in the right direction.