Posts When to use BehaviorSubject
Post
Cancel

When to use BehaviorSubject

I was searching for a concrete example on when and how to use RxJs BehaviorSubect. So I found an example in a Shopping cart web application. The BehaviorSubject is used in a shopping cart service. Here is an example of its implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
export class GlobalService {

    cart$: BehaviorSubject<Cart> = new BehaviorSubject(new Cart);
    lineItems$: BehaviorSubject<LineItem[]> = new BehaviorSubject([]);

    constructor() {
        let cart = new Cart;
        this.cart$.next(cart);
    }


    get cart() {
        return this.cart$.getValue();
    }

    set cart(cart) {
        this.cart$.next(cart);
    }

    set lineItems(lineItems) {
        this.lineItems$.next(lineItems);
    }

    get lineItems() {
        return this.lineItems$.getValue();
    }

    addItemToCart(variant: Variant) {
        let quant = prompt("You want to add " + variant.title + " to the cart. Please, enter quantity", '1')
        this.lineItems.push(
            {
                id: '',
                title: variant.title,
                quantity: +quant,
                variant: variant,
            }
        );
        this.lineItems = this.lineItems;
    }

    removeItemFromCart(i) {     
        this.lineItems.splice(i, 1);
    }
}
This post is licensed under CC BY 4.0 by the author.