A few months after that project I started to notice RxJS. It seemed like a really good way to program asynchronous code. After reading through the docs and examples, I wanted to take it for a test run on that project. A good reference on what reactive programming Checkout this article explaining reactive programming written by Andre Staltz.
I’ll use the following xml to demonstrate what a successful and error api result would look like.
<row>This is the stuff I want</row>
<row>More stuff I want</row>
<error>Something went wrong</error>
xml-stream will parse and stream the xml response chunk by chunk firing off events for specific xml nodes. For this example I want to look for row nodes or error nodes. Row nodes will be inserted into the database and error nodes will not.
To use RxJS for this I’ll create two streams. One stream will make the http request to the api, parse the xml and emit streams for the matching row or error xml nodes. I’ll call that apiStream. The other stream takes values from apiStream and will insert into a database (remember only values from the row xml nodes). I’ll call that stream databaseStream. Finally I’ll subscribe to the databaseStream from where I can handle the success/error/completed events.
var hyperquest = require('hyperquest');
I’m still learing but this was a big improvement from my previous version. For me it’s simpler understanding what’s going on. I’m excited to include RxJS in future projects!