EddyVerbruggen / nativescript-local-notifications

:mailbox: NativeScript plugin to easily schedule local notifications
MIT License
162 stars 57 forks source link

Angular Subject.next doesn't work in callback #164

Closed hrueger closed 5 years ago

hrueger commented 5 years ago

Type: Bug Angular 8 + Nativescript

I have a subject in my push notification service (this service shows the notifications), which is returned as an Observable. But when I do this.subject.next(xxx) in the callback of the local notification, the subscribe method of the observable is not run. But when my component calls the testSubject() Function, subscribe() is run. Why?

test.component.ts

…

constructor(private pushService: PushService) {}

ngOnInit() {
  this.pushService.getSubjectObservable().subscribe(change => {
    console.log("New data", change);
  }
  // Works!
  this.pushService.sendTest("testdata");
}

push.service.ts

...
public subject = new Subject<any>();

constructor() {
  LocalNotifications.addOnMessageReceivedCallback(
      function (notification) {
        // Doesn't work
        this.subject.next(notification);
      }
  ).then(
      function() {
        console.log("Listener added");
      }
  )
}

public getSubjectObservable() {
  return this.subject.asObservable();
}

public sendTest(text) {
  this.subject.next(text);
}
NickIliev commented 5 years ago

@hrueger most likely the LocalNotifications.addOnMessageReceivedCallback changes the meaning of this as this is a native callback. Try the following:

constructor() {
  const that = this;

  LocalNotifications.addOnMessageReceivedCallback(
      function (notification) {
        that.subject.next(notification);
      }
  ).then(
      function() {
        console.log("Listener added");
      }
  )
}
hrueger commented 5 years ago

@NickIliev Thanks for your answer. Although it didn't fix the problem, I wondered why there is no error if this.subject didn't exist. So I printed both subjects (the one in the sendTest() method and the one in the callback) and noticed, that the subject in the callback doesn't have any subscribers... The problem was that I added the callback, before I subscribed to the subject... I fixed this by adding the callback again after the subscribe. Nevertheless, many thanks for your efforts!