notifyManager.mjs 1.9 KB

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