Skip to content

Commit

Permalink
notif: Better abstract the listen and unlisten operations.
Browse files Browse the repository at this point in the history
The wix library gives one API in the iOS case, and a quite different
-- and much less reasonable -- one in the Android case.  The main
point of this change is to cover those with a single, reasonable,
abstraction.

This should be a pure refactor in the iOS case.

In the Android case, this ensures we don't end up with two of these
listeners for `notificationOpened`.  That isn't likely in practice,
because this is made by AppEventHandlers which is far to the outside
of our React tree... but better to make it right.

Also add some jsdoc -- mainly to clarify which of these methods are
intended as private helpers and which are the external interface of
this class, as we've added more private helpers.
  • Loading branch information
gnprice committed Jan 29, 2019
1 parent 42adfb3 commit 8ee1793
Showing 1 changed file with 30 additions and 7 deletions.
37 changes: 30 additions & 7 deletions src/notification/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,35 +72,58 @@ export const handleInitialNotification = async (dispatch: Dispatch, usersById: U
}
};

/**
* Listens for notification-related events.
*
* An instance of this doesn't affect the subscriptions of any other
* instance, or anything else.
*/
export class NotificationListener {
dispatch: Dispatch;
usersById: UserIdMap;
unsubs: Array<() => void> = [];

constructor(dispatch: Dispatch, usersById: UserIdMap) {
this.dispatch = dispatch;
this.usersById = usersById;
}

/** Private. */
listen(name: string, handler: (...empty) => void | Promise<void>) {
if (Platform.OS === 'ios') {
NotificationsIOS.addEventListener(name, handler);
this.unsubs.push(() => NotificationsIOS.removeEventListener(name, handler));
}
const subscription = DeviceEventEmitter.addListener(name, handler);
this.unsubs.push(() => subscription.remove());
}

/** Private. */
unlistenAll() {
while (this.unsubs.length > 0) {
this.unsubs.pop()();
}
}

/** Private. */
handleNotificationOpen = (notification: Object) => {
handleNotificationMuddle(notification, this.dispatch, this.usersById);
};

/** Start listening. Don't call twice without intervening `stop`. */
start() {
if (Platform.OS === 'ios') {
NotificationsIOS.addEventListener('notificationOpened', this.handleNotificationOpen);
this.listen('notificationOpened', this.handleNotificationOpen);
} else {
DeviceEventEmitter.addListener('notificationOpened', notification =>
this.listen('notificationOpened', notification =>
this.handleNotificationOpen({ getData: () => notification }),
);
}
}

/** Stop listening. */
stop() {
if (Platform.OS === 'ios') {
NotificationsIOS.removeEventListener('notificationOpened', this.handleNotificationOpen);
} else {
// do nothing
}
this.unlistenAll();
}
}

Expand Down

0 comments on commit 8ee1793

Please sign in to comment.