RxJS/Examples : Différence entre versions

De WikiSys
Aller à : navigation, rechercher
(BehaviorSubject)
Ligne 3 : Ligne 3 :
 
;run : node BehaviorSubject_with_math_random.js
 
;run : node BehaviorSubject_with_math_random.js
 
* https://medium.com/@luukgruijs/understanding-rxjs-behaviorsubject-replaysubject-and-asyncsubject-8cc061f1cfc0
 
* https://medium.com/@luukgruijs/understanding-rxjs-behaviorsubject-replaysubject-and-asyncsubject-8cc061f1cfc0
 +
 +
The BehaviorSubject has the characteristic that it stores the “current” value.
 +
 +
This means that you can always directly '''get the last emitted value from the BehaviorSubject'''.
  
 
<pre>
 
<pre>

Version du 17 juillet 2019 à 14:16

BehaviorSubject

run 
node BehaviorSubject_with_math_random.js

The BehaviorSubject has the characteristic that it stores the “current” value.

This means that you can always directly get the last emitted value from the BehaviorSubject.

const { BehaviorSubject } = require('rxjs');

const subject = new BehaviorSubject();

// subscriber 1
subject.subscribe((data) => {
    console.log('Subscriber A:', data);
});

subject.next(Math.random());
subject.next(Math.random());

// subscriber 2
subject.subscribe((data) => {
    console.log('Subscriber B:', data);
});

subject.next(Math.random());

console.log('last value is',subject.value)
Subscriber A: undefined
Subscriber A: 0.4146420171477112

Subscriber A: 0.7119229539094283
Subscriber B: 0.7119229539094283

Subscriber A: 0.35552417639128375
Subscriber B: 0.35552417639128375
last value is 0.35552417639128375

user.service.ts

 import { Subject } from 'rxjs/Subject';

 export class UserService {
    private users: User[] = [
	{
	    firstName: 'William',
	    lastName: 'Jones',
	    email: 'william.jones@gmx.com',
	    drinkPreference: 'jus d\'orange',
	    hobbies : ['coder', 'boire du café']
	}
    ];
    userSubject = new Subject<User[]>();

    emitUsers() {
	this.userSubject.next(this.users.slice());
    }

    addUser(user: User) {
	this.users.push(user);
	this.emitUsers();
    }
 }