Ionic 2 observables

Hi iam developing an app, where i have userService class, that manages user data. Here i create observable like this :

export class UserService {
  currentUser;
  userObservable;
  userObserver;

  constructor(public http: Http,private db:Database, private platform:Platform) {

this.platform.ready().then(()=>{
  this.userObservable=Observable.create(observer=>{
    this.userObserver=observer;
    setTimeout(()=>{
      this.getCurrentUser().then((data)=>{
        this.userObserver.next(this.currentUser);
      });
    },600);

  }).publish();
  this.userObservable.connect();
});
  }

  saveUser(user){
this.db.insertUserToUsers(user).then(()=>{
  this.currentUser=user;
  this.userObserver.next(this.currentUser);
});
  }

  getCurrentUser(){
return new Promise(resolve=>{
  this.db.getUser().then((data)=>{
    this.currentUser=data;
    resolve(this.currentUser);
  });
});

}

Then i subscribe to it at home page and at user page in constructor like this :

this.platform.ready().then(() => {
      this.userService.getCurrentUser().then((data)=>{
        this.currentUser=data;
      });
      this.userSubscription=this.userService.userObservable.subscribe((data)=>{
        console.log(data);
        this.currentUser=data;
      });

The problem is, the observable start to emit values,everything is ok but homepage, but it doesnt work on user page, because it isnt subscribed in the moment when the observable starts emitting. Is there any way to fix this problem? If i use observable without publish() and connect(), it doesnt work too, because for some reason - home page subscription ok, user page subscription ok, but after this, the first subscription(subscription from home page) stops to work. Any ideas?

I think you’re overthinking the design, and you probably don’t need to be explicitly creating Observables like that, but in any case I suspect you’re getting caught up in the difference between hot and cold observables. There are many posts on the topic: here is one.

I know about cold and hot observables, cold observable would be much better, but when i use it, the first subscription ends, when the second begins. How can i solve this? Or any tips, how can i make it without explicitly creating Observables like this?

first of all --> do not do this whole async stuff in the constructor of the service.

Simply call getCurrentUser in your component or where you need it.

Thats it. If you want to subscribe and get informed if there is a current user --> store the current User in your service and return it with Observable.of(this.user) instead of creating an observable on your own.

If you want to inform other parts like hot observables --> read about Subjects. You can subscribe subjects and run next on it to spread new or changed data.

thx a lot :slight_smile: Subjects is the answer :slight_smile: To be precise Behavioral Subject solved my problem… one final question. Are Observables and Subjects problem for app performance?