# Can I subscribe Observable from service provider?

**URL:** <https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713>\
**Category:** ionic-v3\
**Created:** [December 7, 2017, 7:53pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713 "2017-12-07T19:53:24Z")\
**Posts on this page:** 13\
**Page:** 1

<div class="post-metadata">

**Author:** ![JeffMinsungKim](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@JeffMinsungKim](https://forum.ionicframework.com/u/JeffMinsungKim)\
**Post date:** [December 7, 2017, 7:53pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/1 "2017-12-07T19:53:24Z")

</div>

Hello guys. I have one question to ask. I’m kinda new to Ionic so I wonder whether I could subscribe observable from service or not. If so, how can I unsubscribe it when the user signs out from my application?

This is my user service provider.

user-service.ts

```auto
 getCurrentUsername() {
    return this.afDB.object(`users/${this.currentUserId}/username`).valueChanges();
  }

sendFriendRequest(recipient: string) {
    let senderInfo = {
      sender: this.currentUserId,
      username: // I would like to include username as an object.
      timestamp: Date.now(),
      message: 'wants to be friend with you.'
    }
    return new Promise((resolve, reject) => {
      this.afDB.list(`friend-requests/${recipient}`).push(senderInfo).then(() => {
        resolve({'status': true, 'message': 'Friend request has sent.'});
      }, error => reject({'status': false, 'message': error}));
    });
  }

```

---

<div class="post-metadata">

**Author:** ![jaydz](https://avatars.discourse-cdn.com/v4/letter/j/858c86/32.png) [@jaydz](https://forum.ionicframework.com/u/jaydz)\
**Post date:** [December 7, 2017, 8:21pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/3 "2017-12-07T20:21:48Z")

</div>

You would want to have on your component.ts

```auto
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';

interface User {
  username: string,
  //etc
 }

export class SendMessagePage {
user: User;
observedUser$: Observable<User>;
userSubscription: Subscription;
 constructor() {
      observedUser$ = getCurrentUser();
  }

ionViewDidLoad(){
   userSubscription = observedUser$.subscribe(data => {
    user = data;
   })
  }

ionViewWillLeave(){
  userSubscription.unsubscribe();
  }

  getCurrentUser() {
    return this.afDB.object(`users/${this.currentUserId}`).valueChanges();
  }

   sendFriendRequest(recipient: string){
     let senderInfo = {
      sender: this.currentUserId,
      username: user.username
      timestamp: Date.now(),
      message: 'wants to be friend with you.'
    }
  }
}

```

Get the User, not just the username. Store it in user on ionViewDidLoad, then unsubscribe when the view will leave (That’s what I would do at least).

Of course, you’ll have to modify stuff a little bit since you’ll be getting `getCurrentUser()` from your provider, but the basic idea is the same

```auto
observedUser$ = this.yourProvider.getCurrentUser();

```

---

<div class="post-metadata">

**Author:** ![JeffMinsungKim](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@JeffMinsungKim](https://forum.ionicframework.com/u/JeffMinsungKim)\
**Post date:** [December 7, 2017, 8:49pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/4 "2017-12-07T20:49:47Z")

</div>

Glad to see you again @jaydz and thank you 🙂  
It did help me, so it’s a bad idea to subscribe from the service?

---

<div class="post-metadata">

**Author:** ![jaydz](https://avatars.discourse-cdn.com/v4/letter/j/858c86/32.png) [@jaydz](https://forum.ionicframework.com/u/jaydz)\
**Post date:** [December 7, 2017, 8:56pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/5 "2017-12-07T20:56:10Z")

</div>

Thanks @JeffMinsungKim, good to see you too.

A bad idea? I don’t think it’s a bad idea. A more complicated idea, yes. You could subscribe in your provider, and publish data to your pages with Ionic Events (in the event that data changes).

But yes, you can subscribe in your provider too, then just return the user or user name to the page you need it in. I personally tend not to, but only because it adds a layer of complicated to the process that I simply haven’t needed for the most part.

I just took another look at your question and realized that subscribing FROM the provider was you main concern. Sorry!

As mentioned above, yeah, you totally can. You would just have to add a function to your provider to unsubscribe from observedUser$ and call it on ionViewWillLeave()

---

<div class="post-metadata">

**Author:** ![JeffMinsungKim](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@JeffMinsungKim](https://forum.ionicframework.com/u/JeffMinsungKim)\
**Post date:** [December 7, 2017, 9:02pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/6 "2017-12-07T21:02:28Z")

</div>

@jaydz I’m not quite sure what you’ve just said, but it is more complicated. I get it.

Btw not really sure why I can’t add the subscription to this code. It all works fine on other pages.

```auto
private subscription: Subscription;

ionViewDidLoad(){
   let sub = observedUser$.subscribe(data => {
    user = data;
   })
   this.subscription.add(sub);
  } 

```

---

<div class="post-metadata">

**Author:** ![jaydz](https://avatars.discourse-cdn.com/v4/letter/j/858c86/32.png) [@jaydz](https://forum.ionicframework.com/u/jaydz)\
**Post date:** [December 7, 2017, 9:07pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/7 "2017-12-07T21:07:23Z")

</div>

```auto
this.subscription = observedUser$.subscribe(data => {
user = data
})
ionViewWillLeave(){
this.subscription.unsubscribe()
}

```

Sorry, forgot to add

```auto
this 

```

In my first post

So it would be

```auto
this.userSubscription = observedUser$.subscribe(data

```

---

<div class="post-metadata">

**Author:** ![JeffMinsungKim](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@JeffMinsungKim](https://forum.ionicframework.com/u/JeffMinsungKim)\
**Post date:** [December 7, 2017, 9:10pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/8 "2017-12-07T21:10:28Z")

</div>

Oh, I know what breaks my code.  
I’m actually subscribing multiple things so that’s why I tried to use add() method. Anyways thank you, everything works fine now 🙂

---

<div class="post-metadata">

**Author:** ![jaydz](https://avatars.discourse-cdn.com/v4/letter/j/858c86/32.png) [@jaydz](https://forum.ionicframework.com/u/jaydz)\
**Post date:** [December 7, 2017, 9:17pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/9 "2017-12-07T21:17:02Z")

</div>

You can do this.

```auto
userSubscription: Subscription;
subscriptionArray: Subscription[];

```

```auto
this.userSubscription = observedUser$.subscribe(data = {
 user = data;
 })
this.subscriptionArray = [userSubscription, //other subscription]

```

On viewWillLeave

```auto
ionViewWillLeave(){
this.subscriptionArray.filter(sub => sub !== undefined).map(subs => subs.unsubscribe())
 }

```

I filter the subscription array for subscriptions that were not initialized based on code. But mapping the array of subscriptions to unsubscribe is probably what you’re looking for. At least, it’s a method that will work.

Using this.subscriptionArray.add(this.userSubscription) might work too, I just have never tried that syntax is all  
(though I’m not sure `.add` is meant for that purpose)

---

<div class="post-metadata">

**Author:** ![JeffMinsungKim](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@JeffMinsungKim](https://forum.ionicframework.com/u/JeffMinsungKim)\
**Post date:** [December 7, 2017, 9:20pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/10 "2017-12-07T21:20:28Z")

</div>

Yeap I’ve done it like that 😄  
I’m sorry but one more thing @jaydz .  
I’m currently unsubscribing from ngOnDestroy()  
It seems like much more safer than using ionic lifecycle hook to me. What do you think about that?  
Should I stick with the ionic page leave method?

```auto
ngOnDestroy() {
    if (this.subscription !== undefined) {
      this.subscription.unsubscribe();
    }
  }

```

---

<div class="post-metadata">

**Author:** ![jaydz](https://avatars.discourse-cdn.com/v4/letter/j/858c86/32.png) [@jaydz](https://forum.ionicframework.com/u/jaydz)\
**Post date:** [December 7, 2017, 9:22pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/11 "2017-12-07T21:22:04Z")

</div>

Yeah, I would stick with the lifecycle hook

---

<div class="post-metadata">

**Author:** ![JeffMinsungKim](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@JeffMinsungKim](https://forum.ionicframework.com/u/JeffMinsungKim)\
**Post date:** [December 7, 2017, 9:23pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/12 "2017-12-07T21:23:44Z")

</div>

Great! I better go fix my code.  
Let’s keep in touch @jaydz Thank you for your time!

---

<div class="post-metadata">

**Author:** ![jaydz](https://avatars.discourse-cdn.com/v4/letter/j/858c86/32.png) [@jaydz](https://forum.ionicframework.com/u/jaydz)\
**Post date:** [December 7, 2017, 9:26pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/13 "2017-12-07T21:26:08Z")

</div>

No problem at all. Have fun!

---

<div class="post-metadata">

**Author:** ![mhartington](https://sea1.discourse-cdn.com/ionicframework/user_avatar/forum.ionicframework.com/mhartington/32/137757_2.png) [@mhartington](https://forum.ionicframework.com/u/mhartington)\
**Post date:** [July 19, 2021, 10:00pm UTC](https://forum.ionicframework.com/t/can-i-subscribe-observable-from-service-provider/114713/14 "2021-07-19T22:00:35Z")

</div>


