Application Android et IOS pour l'amicale des élèves
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.

AsyncStorageManager.js 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // @flow
  2. import {AsyncStorage} from "react-native";
  3. /**
  4. * Static class used to manage preferences.
  5. * Preferences are fetched at the start of the app and saved in an instance object.
  6. * This allows for a synchronous access to saved data.
  7. */
  8. export default class AsyncStorageManager {
  9. static instance: AsyncStorageManager | null = null;
  10. /**
  11. * Get this class instance or create one if none is found
  12. * @returns {ThemeManager}
  13. */
  14. static getInstance(): AsyncStorageManager {
  15. return AsyncStorageManager.instance === null ?
  16. AsyncStorageManager.instance = new AsyncStorageManager() :
  17. AsyncStorageManager.instance;
  18. }
  19. // Object storing preferences keys, default and current values for use in the app
  20. preferences = {
  21. showIntro: {
  22. key: 'showIntro',
  23. default: '1',
  24. current: '',
  25. },
  26. proxiwashNotifications: {
  27. key: 'proxiwashNotifications',
  28. default: '5',
  29. current: '',
  30. },
  31. proxiwashWatchedMachines: {
  32. key: 'proxiwashWatchedMachines',
  33. default: '[]',
  34. current: '',
  35. },
  36. nightMode: {
  37. key: 'nightMode',
  38. default: '0',
  39. current: '',
  40. },
  41. expoToken: {
  42. key: 'expoToken',
  43. default: '',
  44. current: '',
  45. },
  46. debugUnlocked: {
  47. key: 'debugUnlocked',
  48. default: '0',
  49. current: '',
  50. }
  51. };
  52. /**
  53. * Set preferences object current values from AsyncStorage.
  54. * This function should be called at the app's start.
  55. *
  56. * @return {Promise<void>}
  57. */
  58. async loadPreferences() {
  59. let prefKeys = [];
  60. // Get all available keys
  61. for (let [key, value] of Object.entries(this.preferences)) {
  62. prefKeys.push(value.key);
  63. }
  64. // Get corresponding values
  65. let resultArray: Array<Array<string>> = await AsyncStorage.multiGet(prefKeys);
  66. // Save those values for later use
  67. for (let i = 0; i < resultArray.length; i++) {
  68. let key: string = resultArray[i][0];
  69. let val: string | null = resultArray[i][1];
  70. if (val === null)
  71. val = this.preferences[key].default;
  72. this.preferences[key].current = val;
  73. }
  74. }
  75. /**
  76. * Save the value associated to the given key to preferences.
  77. * This updates the preferences object and saves it to AsynStorage.
  78. *
  79. * @param key
  80. * @param val
  81. */
  82. savePref(key: string, val: string) {
  83. this.preferences[key].current = val;
  84. AsyncStorage.setItem(key, val);
  85. }
  86. }