A simple example of an Observable/Subscribe function in TypeScript

I had to work with Observables in JavaScript (RxJS) today and found it, well, bloody hard to find some good examples.

Actually, it’s hard to know what to even search for to find information about Observables (do I search in relation to Angular, Javascript, ECMAScript, TypeScript…?). I found it even harder to decipher most of the highly technical documentation that has been written.

Most examples I found were around making HTTP calls to a server and went no further.

The problem I was solving was to wait for a function that received the results of an HTTP call to finish before then executing other code. That is:

main() — calls –> load() — calls –> httpRequester()

What I need is for load() to return an Observable to main() so I can schedule other code to run only once httpRequester(), and hence load(), where both finished.

After half an hour of looking at examples I figured it out, and for everyone’s benefit, I have created a simple and hopefully easy to understand example on StackBilitz.

Running Example

NOTE: You can pop the editor open in a new window by selecting “Edit On StackBlitz” in the bottom-left of the inserted window.

If you’re using Internet Explorer or there’s just a black window below, here’s the link to the code (and I suggest using a “modern” browser – Chrome and Edge both work): https://stackblitz.com/edit/typescript-vtrstc.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.