Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of pipe operators RXJS Angular 5

Is it me, or is the order of my operators not right? In the code below, the two taps with the console.logs return the same values. That can't be right right?

return this.pcs.getAvailableMaterials(currentProduct.id).pipe(
            map(
                result => result.result.data
            ),
            tap(
                x => console.log(x, 'before')
            ),
            map(
                materials => {
                    materials.forEach(material => {
                        material.type = 'material'
                    })
                    return materials
                }
            ),
            tap(
                x => console.log(x, 'after')
            ),
            tap(
                materials => {
                    setState({
                        ...state,
                        availableMaterials: materials
                    })
                }
            )
        )

Angular 5 application with NGXS.

like image 245
Dirk Avatar asked Oct 19 '25 13:10

Dirk


1 Answers

NOTE that @samanime's answer is not correct. Consider the following modification to your original code:

return this.pcs.getAvailableMaterials(currentProduct.id).pipe(
        ...
        tap(
            x => console.log(x, 'before')
        ),
        map(
            materials => {
                materials.forEach(material => {
                    material.type = 'material'
                })
                return materials
            }
        ),
        delay(1000), // this line is new
        tap(
            x => console.log(x, 'after')
        ),
        ...
    )

You still see both logs as the same. For @samanime's answer to be correct, console.log would somehow have to be taking a full second to execute, which is certainly not the case.

The issue here is that RXJS expects pipe functions to be pure. That is, no pipe function should create any side effects that persist outside the execution of that function. In your first map call, you mutate the objects inside the materials array and then return a reference to the same array. This is a side effect. To fix this, you should be returning a new array from the first map call. Something like:

map(
  materials =>
    materials.map(material => { // map instead of forEach makes a new array
      return {...material, type: 'material'} // object spread makes new objects
    })
)

This should give you what you expect.

like image 165
ethan.roday Avatar answered Oct 21 '25 05:10

ethan.roday



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!