pressureObserverWrapper.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { Observable } from "./observable.js";
  2. /**
  3. * A wrapper for the experimental pressure api which allows a callback to be called whenever certain thresholds are met.
  4. */
  5. export class PressureObserverWrapper {
  6. /**
  7. * A pressure observer will call this callback, whenever these thresholds are met.
  8. * @param options An object containing the thresholds used to decide what value to to return for each update property (average of start and end of a threshold boundary).
  9. */
  10. constructor(options) {
  11. this._observer = null;
  12. this._currentState = [];
  13. /**
  14. * An event triggered when the cpu usage/speed meets certain thresholds.
  15. * Note: pressure is an experimental API.
  16. */
  17. this.onPressureChanged = new Observable();
  18. if (PressureObserverWrapper.IsAvailable) {
  19. this._observer = new PressureObserver((update) => {
  20. this._currentState = update;
  21. this.onPressureChanged.notifyObservers(update);
  22. }, options);
  23. }
  24. }
  25. /**
  26. * Returns true if PressureObserver is available for use, false otherwise.
  27. */
  28. static get IsAvailable() {
  29. return typeof PressureObserver !== "undefined" && PressureObserver.supportedSources.includes("cpu");
  30. }
  31. /**
  32. * Method that must be called to begin observing changes, and triggering callbacks.
  33. * @param source defines the source to observe
  34. */
  35. observe(source) {
  36. try {
  37. this._observer?.observe(source);
  38. this.onPressureChanged.notifyObservers(this._currentState);
  39. }
  40. catch {
  41. // Ignore error
  42. }
  43. }
  44. /**
  45. * Method that must be called to stop observing changes and triggering callbacks (cleanup function).
  46. * @param source defines the source to unobserve
  47. */
  48. unobserve(source) {
  49. try {
  50. this._observer?.unobserve(source);
  51. }
  52. catch {
  53. // Ignore error
  54. }
  55. }
  56. /**
  57. * Release the associated resources.
  58. */
  59. dispose() {
  60. this._observer?.disconnect();
  61. this._observer = null;
  62. this.onPressureChanged.clear();
  63. }
  64. }
  65. //# sourceMappingURL=pressureObserverWrapper.js.map