Let start with this:

If we run this code nothing will happen right? But why?

The answer is because observable are lazy computations and if we don’t subscribe to them nothing will happened.

This is how we subscribe to this observable. Now if I run I well get a result.

What is the difference between observables and functions?

The main difference is that you can call multiple times with multiple values and basically return multiple values and possibly at different times.

When we now run this, we see 7, 777, and 7777 and 5555 after 5 seconds

When you call a function, you’re basically saying, ” het function give me a value immediately, and just one value using the return keyword”. But when you’re saying subscribe on an observable , you’re saying, “hey observable I give me values from now and until I unsubscribe or until you are complete”. I don’t know, maybe they come immediately. Maybe it’s just one. Maybe they are asynchronous.

Ok so far we know observables are almost like functions but allow you to return many values.

Now Lets explore on another concept Generator functions, which do something very similar.

We can create a generator with

Notice the * after function keyword. I’m going to yield a value, 7;, which is the generator style of giving a value.

Then I’m going to yield more values, 77 and 777.

As with observables, this is a  lazy computation, so nothing will happen until we ask for these values. We do this by getting an iterator when calling this function myGenerator().

Once we have that iterator, we can get values from that by saying iterator.next().value.

If we run this, we see hello 7 and 77.

How does that differ from observables?

The way its usually seen is with observables :

Is the Producer of values and the subscriber Is the consumer of values

With generators on the other hand :

Is producing values and

is consuming those values.

The main different is that with observables the Producer determines when the values are sent (Push style) and with generators the consumer determines when values are sent (Pull style)

Generator functions are more useful as a passive factory of values. and with generators, the values are pulled from the consumer.

LEAVE A REPLY

Please enter your comment!
Please enter your name here