notifyManager.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var utils = require('./utils.js');
  4. function createNotifyManager() {
  5. let queue = [];
  6. let transactions = 0;
  7. let notifyFn = callback => {
  8. callback();
  9. };
  10. let batchNotifyFn = callback => {
  11. callback();
  12. };
  13. const batch = callback => {
  14. let result;
  15. transactions++;
  16. try {
  17. result = callback();
  18. } finally {
  19. transactions--;
  20. if (!transactions) {
  21. flush();
  22. }
  23. }
  24. return result;
  25. };
  26. const schedule = callback => {
  27. if (transactions) {
  28. queue.push(callback);
  29. } else {
  30. utils.scheduleMicrotask(() => {
  31. notifyFn(callback);
  32. });
  33. }
  34. };
  35. /**
  36. * All calls to the wrapped function will be batched.
  37. */
  38. const batchCalls = callback => {
  39. return (...args) => {
  40. schedule(() => {
  41. callback(...args);
  42. });
  43. };
  44. };
  45. const flush = () => {
  46. const originalQueue = queue;
  47. queue = [];
  48. if (originalQueue.length) {
  49. utils.scheduleMicrotask(() => {
  50. batchNotifyFn(() => {
  51. originalQueue.forEach(callback => {
  52. notifyFn(callback);
  53. });
  54. });
  55. });
  56. }
  57. };
  58. /**
  59. * Use this method to set a custom notify function.
  60. * This can be used to for example wrap notifications with `React.act` while running tests.
  61. */
  62. const setNotifyFunction = fn => {
  63. notifyFn = fn;
  64. };
  65. /**
  66. * Use this method to set a custom function to batch notifications together into a single tick.
  67. * By default React Query will use the batch function provided by ReactDOM or React Native.
  68. */
  69. const setBatchNotifyFunction = fn => {
  70. batchNotifyFn = fn;
  71. };
  72. return {
  73. batch,
  74. batchCalls,
  75. schedule,
  76. setNotifyFunction,
  77. setBatchNotifyFunction
  78. };
  79. } // SINGLETON
  80. const notifyManager = createNotifyManager();
  81. exports.createNotifyManager = createNotifyManager;
  82. exports.notifyManager = notifyManager;
  83. //# sourceMappingURL=notifyManager.js.map