I’m trying to use Rx to write an asynchronous DataContext for linq-to-sql on Windows Phone 7.5. My idea is to define a method in the DataContext:
IObservable<List<Fact>> GetFacts(Func<MyDataContext, IQueryable<Fact>> selector)
{
var selectFacts = Observable.FromAsyncPattern<MyDataContext, IQueryable<Fact>>(selector.BeginInvoke, selector.EndInvoke);
return selectFacts(db).Select((query) => query.ToList());// db variable is MyDataContext instance, and is not null during the call or later
}
This method should then be called from the client code, like this:
var q = GetFacts((database) => from item in database.Facts select item)
.ObserveOnDispatcher()
.Do((facts) => MessageBox.Show(facts.Count.ToString()))
.Subscribe();
The problem I’m facing is quite strange. When the client selector (from item in database.Facts select item) is actually called, the database parameter in it’s context is null! Therefore, I’m obviously getting the NullReferenceException. But when the selectFacts is called, the db value is non-null, and points to correct instance.
Are there any explanations to this fact? How to overcome it?
Thanks in advance.
I think you’re going about this in a very strange way. If you want to run code in the background and have it return an
IObservable<T>(like Task), you should useObservable.Start: