Can I use multiple subscribers to one publishing events?

I am using Events to implement event-and-listen feature.

I am trying to implement two subscribers to one publishing events.
One of them can receive the data, but the other cannot.
The one which cannot receive the data has another subscribing code about different events.

I don’t know what’s wrong. Is it possible to write multiple subscribers in one class?
Is it possible to have multiple subscribers to one publishing events?

What should I do? Could you give me some advice?
Thank you in advance. :slight_smile:

export class TransactionPage {
   transaction: any;
   
   doTransaction() {
      events.publish('user:transaction', transaction);
   }
}
export class HomePage {
   this.events.subscribe('user:login', (data)=>{
      // This is another subscribing code for different event 
      // I can receive 'data' well
   });
   this.events.subscribe('user:transaction', (data)=>{
      // This code works but I cannot receive 'data'
   });
}
export class NavigationDrawerPage {
    this.events.subscribe('user:transaction', (data)=>{
      // I can receive 'data' well.
   });
}

is this possible? did you get it to work?

1 Like

I think I solved this problem by using the independent servers.

  • An event occurs.
doTransaction() {
    postTransactionDataToServer(transaction);
    events.publish('user:transaction');
}
  • The data changes in the server.
  • Try to receive the changed data from the server when subscribe handlers occur.
// You should receive the data from the server in the method 
// where you should check the changed data
this.events.subscribe('user:transaction', () => {
    transaction = getTransactionDataFromTheServer();
});

I hope it would help.

2 Likes

Thank you. That should work for me too… So events itself takes a single subscriber

No, I didn’t mean that.
What I said is that multiple subscribers can receive the changed data by using the independent server.
So, you can use the code to receive the data in multiple places.

(Scenario)
An event occurs -> change data and post the data into the server -> data changed in the server -> multiple subscribers receive the data from the server -> Now, every places which should have the changed data have the data! -> Yay!

It looks like you have to use named functions for both subscribers to work; since subscribers are maintained internally, you are overwriting one subscriber with another. Try using named functons instead:

....
private _onUserTransactionA(data: any) {
    // i should receive data
}

this.events.subscribe('user:transaction', this._onUserTransactionA);

private _onUserTransactionB(data: any) {
    // i should receive also receive data
}

this.events.subscribe('user:transaction', this._onUserTransactionB);
1 Like

oh…alright…will try it out.thanks guys

1 Like