'Capacitor plugin addListener RxJs style

I would like to write this:

PushNotifications.addListener('registration', (token: Token) => {
   console.log('Push registration success, token: ' + token.value);
});

in RxJs style. I tried using fromEventPattern but I get:

Argument of type 'PushNotificationsPlugin' is not assignable to parameter of type '(handler: NodeEventHandler) => any'.

EDIT:

I tried with:

register() {
  const addPushNotificationListener = (handler: (token: Token) => void) => {
      PushNotifications.addListener('registration', handler);
  };
  return fromEventPattern(addPushNotificationListener)
    .pipe(
      map((token: Token) => this.token = token)
  );
}

But it's not working at all.. the map function is never called.

EDIT II:

Full code:

/** PushNotificationsService */

@Log()
requestPermissionsAndRegister() {
  return this.requestPermissions()
  .pipe(
    filter(permissionGranted => permissionGranted),
    switchMap(() => this.register())
  );
}


@Log()
private requestPermissions(): Observable<boolean> {
  return from(PushNotifications.requestPermissions())
    .pipe(
      map((status: PermissionStatus) => status.receive === 'granted')
    );
}

@Log()
private register() {
  const addPushNotificationListener = (handler) => {
    PushNotifications.addListener('registration', handler);
  };
  return fromEventPattern(addPushNotificationListener)
    .pipe(
      map((token: Token) => this.token = token)
    );
}

And from another class:

this.pushNotificationService.requestPermissionsAndRegister()
  .subscribe()


Solution 1:[1]

If I follow the example here fromEventPattern:

function addPushNotificationListener(handler) {
  PushNotifications.addListener('registration', handler);
};

const push$ = fromEventPattern(addPushNotificationListener);

Of course you should also add a remove handler.

Solution 2:[2]

I was not calling PushNotifications.register();, the following code works:

private register() {

  PushNotifications.register();

  const addPushNotificationListener = (handler) => {
    PushNotifications.addListener('registration', handler);
  };
  return fromEventPattern(addPushNotificationListener)
    .pipe(
      map((token: Token) => this.token = token)
    );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 daflodedeing
Solution 2 Ernesto Schiavo