简体   繁体   中英

How can I turn a synchronous polling database query into an asynchronous push using reactive extensions?

Currently, I'm issuing a database select in NHibernate that returns an IList of results. Then I use IList.ToObservable on the list returned to get an IObservable that I can subscribe to. How can I write this in the reactive paradigm rather than just converting a list to an IObservable ?

The very best way to make database calls using Reactive Extensions is not to do it at all.

Pithy one-liners aside, this is a serious point. The clue is in the question... you are making an IO bound call , therefore you are really in a async pull situation.

There'll be first class language support for this in C# 8 (IAsyncEnumerable - which already has placeholders in the Rx github repo ).

But you really don't want to expose a synchronous call response as an Observable when you have initiated a call to which you are expecting a prompt response. Observables are for push scenarios when you don't know if or when data will turn up. You can make your query asynchronous and handle the results more traditionally when they come.

Where you often see async DB queries in Rx is as part of an observable chain rooted in some suitable observable event such as a keypress in a UI. The keypress event is fed into an Observable which in turn projects into an async query and is popped back into the UI. eg: The example here has a service call that could just as easily be an async DB query. The key part is the use of the getSuggestions asynchronous cal and how it is wired in to the observable query.

Note even in this situation the service call itself is still an async pull that is not returning an Observable directly; it's been initiated by some other observed event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM