1

I have a class with more than 30 observable attributes. Each time my server receives a payload containing these 30 attributes I call the next() method for all the corresponding attributes of the instance, so far so good.

The problem is that, sometimes, I have to check for an attribute's value, outside the scope of the observer that subscribed to that observable attribute.
What comes to mind is that I have to have duplicate attributes for everything, one is the observable and the other one is a stateful attribute to save the arriving values for later consumption.
Is there some way to avoid this with a method like: Observable.getCurrentValue()?

As requested, some example code

class Example {
    public subjects = {
        a1: new Subject<any>(),
        a2: new Subject<any>(),
        a3: new Subject<any>(),
        a4: new Subject<any>(),
        a5: new Subject<any>()
    }

    public treatPayload(data: any) {
        for (const prop in data) {
            if (data.hasOwnProperty(prop) && prop in this.subjects){
                Reflect.get(this.subjects, prop).next(data[prop])
            }
        }
    }

    public test() {
        const a1_observable = this.subjects.a1.asObservable()
        const a2_observable = this.subjects.a2.asObservable()

        const example_payload_1 = {
            a1: "first",
            a2: "second",
            a10: "useless"
        }

        const example_payload_2 = {
            a1: "first-second",
            a2: "second-second",
            a10: "useless-second"
        }

        a1_observable.subscribe((a1_new_value: any) => {
            const i_also_want_the_last_value_emitted_by_a2 = a2_observable.last_value() // of course, this doesn't exist
            console.log(a1_new_value)
            console.log(i_also_want_the_last_value_emitted_by_a2)
        })
        
        this.treatPayload(example_payload_1)
        this.treatPayload(example_payload_2)

    }
}

So, is there a way to retrieve the correct value of i_also_want_the_last_value_emitted_by_a2 without a pipe operator? I think it would be a problem to emit all values I could possibly use in a subscriber within a pipe of the a2_observable.

Teodoro
  • 1,194
  • 8
  • 22

1 Answers1

2

You could use BehaviorSubject.value, where you could store your server data.

Andrei Gătej
  • 11,116
  • 1
  • 14
  • 31