Search code examples
angulartypescriptionic-frameworkionic4ionic-native

BehaviorSubject<Object[]> returns faulty array on first .subscribe


I have a BehaviorSubject and the first .subscribe callback returns an Array with 6 Objects and on a console-output, it shows length: 6 but every for-loop only iterates 5 times and even console.log(arr.length) outputs '5'

I do not really know how to reproduce this, but t have following code:

public objects: BehaviorSubject<Object[]> = new BehaviorSubject([]);

// other class
            this.objectService.objects.subscribe(_objects => {
                if (_objects) {
                    for (const obj of _objects) {
                        console.log(obj);
                    }
                    console.log(_objects);
                    console.log(_objects.length);
                }
            });

Output: Output

How can this happen? A lot of different services write (objects.next) to this BehaviorSubject, but how can I prevent this from happening? It only happens the first time 'objects' is .next-ed, from the second .next on this code works perfectly and shows the real length.

I also tested .find and .filter on the array, but it only can filter the 5 last entries and not the first one


Solution

  • First: your Behavior subjects should be either protected or private. Otherwise you are opening to vulnerabilities.

    With that said. You are creating a behavior subject with initial value of ([]). when you subscribe, that value is emitted ([]). Then, the first next() emits a new value. Since both overlap, then you get a 6-length array. If I'm not wrong, this shouldn't happen if you use a Subject() instead of a BehaviorSubject, or is merely a mistake of console.log outputting too much.