3

according to the official docs, I can use a Subject like this: docs

However, I find it a rather theoretical explanation.

I have a strong background in Angular 1.X.

Can someone describe me, the concept 'subject' by comparing it with something in Angular 1.X?

hannes neukermans
  • 12,017
  • 7
  • 37
  • 56
  • 1
    I don't think it's comparable with something AngularJS had. It's new, I would recommend reading the introduction on the website. http://reactivex.io/intro.html – koningdavid Oct 24 '16 at 08:02

3 Answers3

1

Subjects, in a way, are like messengers.

A kingdom dispatches messages to the messenger to notify its allies about an attack at its border. The allies tell the messenger that they will send forces to help out.

To come back to a more technical language:

Subjects are two-way variables. You can subscribe to it to receive updates when it changes, and change the variable by calling next on it and passing a parameter.

Alexander Ciesielski
  • 10,506
  • 5
  • 45
  • 66
0

I found this explanation quite nice:

An observable is like an array where the elements arrive delayed in time.

You can use operators like .forEach(), and .map() (and others).

It also has similarities to Promise but can emit 0 or more values on subscribe() (similar to then() but only calls the callback passed to then() once, while the callback passed to subscribe() can be called multiple times before the emitter resolves the observable).

See also Angular - Promise vs Observable

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

$q.defer() comes very close.
To clarify, 2 equal pieces of code.

//written with $q.defer()
function doWorkAsync() {
   var defer;
   defer = $q.defer();
   getStuff().then(function() {
       defer.resolve('finished here');
   }
   return defer.promise;
}
...
doWorkAsync().then(showResults);


//written with subject()
function doWorkAsync() : Observable<string> {
   let subject$ = new AsyncSubject<string>();

   getStuff().then(function() {
       subject$.next('finished here');
       subject$.complete();
   }
   return subject$;
}
...
doWorkAsync().subscribe(showResults);

To Summarize:

defer.promise ~= observable.
defer.resolve && defer.reject ~= observer.

hannes neukermans
  • 12,017
  • 7
  • 37
  • 56