Source: lib/util/destroyer.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.util.Destroyer');
  7. goog.require('shaka.util.Error');
  8. goog.require('shaka.util.PublicPromise');
  9. /**
  10. * @summary
  11. * A utility class to help work with |shaka.util.IDestroyable| objects.
  12. *
  13. * @final
  14. */
  15. shaka.util.Destroyer = class {
  16. /**
  17. * @param {function():!Promise} callback
  18. * A callback to destroy an object. This callback will only be called once
  19. * regardless of how many times |destroy| is called.
  20. */
  21. constructor(callback) {
  22. /** @private {boolean} */
  23. this.destroyed_ = false;
  24. /** @private {!shaka.util.PublicPromise} */
  25. this.waitOnDestroy_ = new shaka.util.PublicPromise();
  26. /** @private {function():!Promise} */
  27. this.onDestroy_ = callback;
  28. }
  29. /**
  30. * Check if |destroy| has been called. This returning |true| does not mean
  31. * that the promise returned by |destroy| has resolved yet.
  32. *
  33. * @return {boolean}
  34. * @final
  35. */
  36. destroyed() {
  37. return this.destroyed_;
  38. }
  39. /**
  40. * Request that the destroy callback be called. Will return a promise that
  41. * will resolve once the callback terminates. The promise will never be
  42. * rejected.
  43. *
  44. * @return {!Promise}
  45. * @final
  46. */
  47. destroy() {
  48. if (this.destroyed_) {
  49. return this.waitOnDestroy_;
  50. }
  51. // We have started destroying this object, so we should never get here
  52. // again.
  53. this.destroyed_ = true;
  54. return this.onDestroy_().then(
  55. () => { this.waitOnDestroy_.resolve(); },
  56. () => { this.waitOnDestroy_.resolve(); });
  57. }
  58. /**
  59. * Checks if the object is destroyed and throws an error if it is.
  60. * @param {*=} error The inner error, if any.
  61. */
  62. ensureNotDestroyed(error) {
  63. if (this.destroyed_) {
  64. if (error instanceof shaka.util.Error &&
  65. error.code == shaka.util.Error.Code.OBJECT_DESTROYED) {
  66. throw error;
  67. }
  68. throw shaka.util.Destroyer.destroyedError(error);
  69. }
  70. }
  71. /**
  72. * @param {*=} error The inner error, if any.
  73. * @return {!shaka.util.Error}
  74. */
  75. static destroyedError(error) {
  76. return new shaka.util.Error(
  77. shaka.util.Error.Severity.CRITICAL,
  78. shaka.util.Error.Category.PLAYER,
  79. shaka.util.Error.Code.OBJECT_DESTROYED,
  80. error);
  81. }
  82. };