Settings.ios.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. const RCTDeviceEventEmitter = require('../EventEmitter/RCTDeviceEventEmitter');
  12. const invariant = require('invariant');
  13. import NativeSettingsManager from './NativeSettingsManager';
  14. const subscriptions: Array<{
  15. keys: Array<string>,
  16. callback: ?Function,
  17. ...
  18. }> = [];
  19. const Settings = {
  20. _settings: (NativeSettingsManager &&
  21. NativeSettingsManager.getConstants().settings: any),
  22. get(key: string): mixed {
  23. return this._settings[key];
  24. },
  25. set(settings: Object) {
  26. this._settings = Object.assign(this._settings, settings);
  27. NativeSettingsManager.setValues(settings);
  28. },
  29. watchKeys(keys: string | Array<string>, callback: Function): number {
  30. if (typeof keys === 'string') {
  31. keys = [keys];
  32. }
  33. invariant(
  34. Array.isArray(keys),
  35. 'keys should be a string or array of strings',
  36. );
  37. const sid = subscriptions.length;
  38. subscriptions.push({keys: keys, callback: callback});
  39. return sid;
  40. },
  41. clearWatch(watchId: number) {
  42. if (watchId < subscriptions.length) {
  43. subscriptions[watchId] = {keys: [], callback: null};
  44. }
  45. },
  46. _sendObservations(body: Object) {
  47. Object.keys(body).forEach(key => {
  48. const newValue = body[key];
  49. const didChange = this._settings[key] !== newValue;
  50. this._settings[key] = newValue;
  51. if (didChange) {
  52. subscriptions.forEach(sub => {
  53. if (sub.keys.indexOf(key) !== -1 && sub.callback) {
  54. sub.callback();
  55. }
  56. });
  57. }
  58. });
  59. },
  60. };
  61. RCTDeviceEventEmitter.addListener(
  62. 'settingsUpdated',
  63. Settings._sendObservations.bind(Settings),
  64. );
  65. module.exports = Settings;