diff --git a/lib/modules/notifications/index.js b/lib/modules/notifications/index.js index 9a3a739f..b31beebd 100644 --- a/lib/modules/notifications/index.js +++ b/lib/modules/notifications/index.js @@ -33,7 +33,17 @@ import type { Schedule, } from './types'; -type OnNotification = Notification => any; +type BackgroundFetchResultValue = string; + +type BackgroundFetchResult = { + noData: BackgroundFetchResultValue, + newData: BackgroundFetchResultValue, + failure: BackgroundFetchResultValue, +}; + +type CompletionHandler = BackgroundFetchResultValue => void; + +type OnNotification = (Notification, CompletionHandler) => Promise; type OnNotificationObserver = { next: OnNotification, @@ -45,12 +55,6 @@ type OnNotificationOpenedObserver = { next: NotificationOpen, }; -type BackgroundFetchResult = { - noData: string, - newData: string, - failure: string, -}; - const NATIVE_EVENTS = [ 'notifications_notification_displayed', 'notifications_notification_opened', @@ -266,32 +270,36 @@ export default class Notifications extends ModuleBase { onNotificationDisplayed( nextOrObserver: OnNotification | OnNotificationObserver ): () => any { - let listener; - if (isFunction(nextOrObserver)) { - listener = nextOrObserver; - } else if (isObject(nextOrObserver) && isFunction(nextOrObserver.next)) { - listener = nextOrObserver.next; - } else { + const isNext = isFunction(nextOrObserver); + const isObserver = isObject(nextOrObserver) && isFunction(nextOrObserver.next); + if (!isNext && !isObserver) { throw new Error( 'Notifications.onNotificationDisplayed failed: First argument must be a function or observer object with a `next` function.' ); } + let listener: OnNotification; + if (nextOrObserver.next) { + listener = nextOrObserver.next; + } else { + listener = nextOrObserver; + } + + const autoCompletingListener: OnNotification = async (notification, done) => { + const listenerResult = await listener(notification, done); + done(this.backgroundFetchResult.noData); + return listenerResult; + }; + getLogger(this).info('Creating onNotificationDisplayed listener'); - SharedEventEmitter.addListener( - 'onNotificationDisplayed', - listener - ); + SharedEventEmitter.addListener('onNotificationDisplayed', autoCompletingListener); if (hasListeners('onNotificationDisplayed')) { getNativeModule(this).startHandlingNotificationDisplayed(); } return () => { getLogger(this).info('Removing onNotificationDisplayed listener'); - SharedEventEmitter.removeListener( - 'onNotificationDisplayed', - listener - ); + SharedEventEmitter.removeListener('onNotificationDisplayed', autoCompletingListener); if (!hasListeners('onNotificationDisplayed')) { getNativeModule(this).stopHandlingNotificationDisplayed(); }