Search code examples
rxjsrxjs5

How can I remove and add element on Array by index in RxJS way?


So, I have a array of "events":

let events = Rx.Observable.from([1,2,3,4,5,6,7,8,9]);

I can add(push):

let add = function(number){
  events = events.concat([number]);
}

I can remove:

let remove = function(){
  events = events.filter(event => {
  return event != 3;
})
}

My first question: How can I remove and add a element by index in "RxJS" way?

let removeByIndex = function(index){
  //remove by index
}

let addByIndex = function(index){
  //add by index
}

My second question: I need "reinvent the wheel" for all basic methods of Array on RxJS from and of?


Solution

  • What's your purpose? Your Observable is just a publisher which is listen somewhere in your application?

    In this case, you can just have a method publish where push your new array:

    class EventStream {
        private numbers$: Subject<number[]> = new Subject();
        //or BehaviorSubject if you want a default value
    
        publish(arrayNumberToPublish: number[]): void {
            this.numbers$.next(arrayNumberToPublish);
        }
    
        listen(): Observable<number[]> {
            return this.numbers$;
        }
    }
    

    In your code you listen the stream: new EventStream().listen().(...)

    The second possibility is you want keep the array. I use it when I want stub a CRUD API:

    class EventManager {
        private events: number[] = [];
        private events$: Subject<number[]> = new Subject();
        //or BehaviorSubject if you want a default value
    
        getAllEvents(): Observable<number[]> {
            return this.events$;
        }
    
        addEvent(index: number): void {
            this.events = this.events.concat(index);
            this.events$.next(this.events);
        }
    
        removeEvent(index: number): void {
            this.events = this.events.filter((event) => event !== index);
            this.events$.next(this.events);
        }
    }