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.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. };
  42. /**
  43. * Set preferences object current values from AsyncStorage.
  44. * This function should be called at the app's start.
  45. *
  46. * @return {Promise<void>}
  47. */
  48. async loadPreferences() {
  49. let prefKeys = [];
  50. // Get all available keys
  51. for (let [key, value] of Object.entries(this.preferences)) {
  52. prefKeys.push(value.key);
  53. }
  54. // Get corresponding values
  55. let resultArray: Array<Array<string>> = await AsyncStorage.multiGet(prefKeys);
  56. // Save those values for later use
  57. for (let i = 0; i < resultArray.length; i++) {
  58. let key: string = resultArray[i][0];
  59. let val: string | null = resultArray[i][1];
  60. if (val === null)
  61. val = this.preferences[key].default;
  62. this.preferences[key].current = val;
  63. }
  64. }
  65. /**
  66. * Save the value associated to the given key to preferences.
  67. * This updates the preferences object and saves it to AsynStorage.
  68. *
  69. * @param key
  70. * @param val
  71. */
  72. savePref(key: string, val: string) {
  73. this.preferences[key].current = val;
  74. AsyncStorage.setItem(key, val);
  75. }
  76. }