You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

middleware.js 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // @flow
  2. import { APP_WILL_MOUNT, APP_WILL_UNMOUNT } from '../app';
  3. import { MiddlewareRegistry } from '../redux';
  4. import NetworkInfoService from './NetworkInfoService';
  5. import { _storeNetworkInfoCleanup, setNetworkInfo } from './actions';
  6. import { STORE_NAME } from './constants';
  7. import { ONLINE_STATE_CHANGED_EVENT } from './events';
  8. import logger from './logger';
  9. import type { NetworkInfo } from './types';
  10. /**
  11. * Middleware for 'base/net-info' feature.
  12. *
  13. * @param {Store} store - The redux store.
  14. * @returns {Function}
  15. */
  16. // eslint-disable-next-line no-unused-vars
  17. MiddlewareRegistry.register(({ dispatch, getState }) => next => action => {
  18. const result = next(action);
  19. switch (action.type) {
  20. case APP_WILL_MOUNT:
  21. if (NetworkInfoService.isSupported()) {
  22. const networkInfoService = new NetworkInfoService();
  23. const stop = () => {
  24. networkInfoService.stop();
  25. networkInfoService.removeAllListeners();
  26. };
  27. networkInfoService.addListener(
  28. ONLINE_STATE_CHANGED_EVENT,
  29. ({ isOnline, networkType, details }: NetworkInfo) => {
  30. logger.info('Network changed', JSON.stringify({
  31. isOnline,
  32. details,
  33. networkType
  34. }));
  35. dispatch(setNetworkInfo({
  36. isOnline,
  37. networkType,
  38. details
  39. }));
  40. });
  41. dispatch(_storeNetworkInfoCleanup(stop));
  42. networkInfoService.start();
  43. }
  44. break;
  45. case APP_WILL_UNMOUNT: {
  46. const { _cleanup } = getState()[STORE_NAME];
  47. if (_cleanup) {
  48. _cleanup();
  49. dispatch(_storeNetworkInfoCleanup(undefined));
  50. }
  51. }
  52. break;
  53. }
  54. return result;
  55. });