Using observables in ionic


#1

Hi,

I am pretty new to Ionic and just implemented observables in my app code, and I have some questions regarding observables

Sample implementation:

// function
  getEvent() {
    let observable = new Observable(observer => {
        observer.next(somedata);
    });
    return observable;
  }

// subscribe
      this.getEvent().subscribe((someEvent: any) => {
      });

Questions:

  1. Since I created a new observable, do I need to delete that observable to prevent memory leaks? I am sorry if this is a dumb question, but I come from c++ where a new has to be followed by a delete if not memory leaks will occur.

  2. Since I subscribed to the observable, will I need to unsubscribe anywhere in my code?


#2

You don’t need to create Observables like that unless you’re doing something super fancy. Most standard libraries already have Angular shims so async functions return Promises or Observables as appropriate. It’s a lot safer to go with code like that, which has already been community tested. Observables can be hard to debug.

To answer your other question, you do need to unsubscribe from any Observable you create. There is a lot of good discussion on this forum about best practices here. Not everyone agrees on everything, but there have been some great methods presented. One discussion is here: Should I unsubscribe Observables lists?


#3

Thanks for your very informative reply. Do you have any code examples for the part where you said "It’s a lot safer to go with code like that, which has already been community tested."

So you think that I should not use observables? The only reason I was using them is because I saw a tutorial on them for a socket.io implementation.

Full code:

  getEvent() {
    let observable = new Observable(observer => {
      this.socket.on("newEvent", data => {
        observer.next(data);
      });
    });
    return observable;
  }

Basically the observable helps observe incoming events from the server and does the appropriate actions. Is this the correct use?


#4

Well, the first rule is that 99% of tutorials are wrong, because the frameworks are changing so quickly. The tutorial you read might be fine, but the code looks old, even though I believe what you posted still works. But rxjs is on version 6 now, and I bet that tutorial was written when it was at version 4 max. The common practice now is to use creation operators, and the static create method, rather than the constructor. But using the constructor does work. Just be careful.

Also, socket.io isn’t some bizarre tech. There must be some Angular 2 library you can take a look at, with issues and feedback.