RxJS/Examples

De WikiSys
Aller à : navigation, rechercher

Subject

node Subject_with_math_random.js
const { Subject } = require('rxjs');

const subject = new Subject();

// 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: 0.35552417639128375
Subscriber A: 0.4146420171477112
Subscriber A: 0.7119229539094283
Subscriber B: 0.7119229539094283
last value is undefined

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();
    }
 }