Observables, just powerful functions?

Reactive programming is one of the hottest topics today. With libraries like RxJs and big frameworks like React or Angular adopting it, its becoming even more important.

RxJs introduces one main type called Observable. It is the most important concept in the whole library. Most likely you have already heard of concepts like Subscriber or Observer. In this blogpost I want take a look at these concepts and think of a Observable as a powerful function.

Observables are lazy

Observables are lazy. Which means, they don’t do anything until you subscribe to them. The same goes for functions. Let’s have a look at the following snippet.

function foo(){
console.log('The answer to life')
return 42
};

This function does not do anything until we call it with:

console.log(foo())
// or
// console.log(foo.call())

Notice the similarity between this code and the Observable code:

const foo = Rx.Observable.create(function(observer){
console.log('The answer to life'
observer.next(42)
})
foo.subscribe(function(answer){
console.log(answer)
})

Observables and functions are lazy. They both only do stuff when you call them to do so.

Observable can emit multiple values

So far we have seen that a function and a Observable have a lot in common. What is actually the difference between those two? The main difference is that a observable can emit multiple values. Let’s have a look at the following Observable.

const foo = Rx.Observable.create(function(observer){
console.log('Possible answers to life')
observer.next(42)
observer.next(12)
observer.next(13)
})
foo.subscribe(function(answer){
console.log(answer)
})
// Output
'Possible answers to life'
42
12
13

This happens because our Observable calls the callback function we pass in. In reactive programming this callback functions are called Observer. You are allowed to pass in either three callback functions or an Observer object with the properties next, error and complete. As I said before, the main difference between a observable and a function is that a Observable can emit multiple values. You can not do that with a function unless you use something like ES6 generators. But in general a function can only return one value.

But what happens if we would pass in a callback to our function and call it just like an Observable does?

function foo(callback){
console.log('The answer to life')
callback(42)
callback(12)
callback(13)
};
foo(function(answer){
console.log(answer)
})

Notice again the similarity. An Observable basically does the same thing. It notifies your callback functions called Observer.

Like what you’ve read? If you enjoyed this blogpost please clap, share or follow me. Want to apply what you’ve learned in this post and write your own Observable? Then check out my article on “Demystifying Observables” on itnext.