@dxos/async 0.8.4-main.548089c → 0.8.4-main.59c2e9b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1072,6 +1072,78 @@ var DeferredTask = class {
1072
1072
  await this._currentTask;
1073
1073
  }
1074
1074
  };
1075
+ var AsyncTask = class {
1076
+ #callback;
1077
+ #ctx = void 0;
1078
+ #scheduled = false;
1079
+ #currentTask = null;
1080
+ #nextTask = new Trigger();
1081
+ constructor(callback) {
1082
+ this.#callback = callback;
1083
+ }
1084
+ get scheduled() {
1085
+ return this.#scheduled;
1086
+ }
1087
+ /**
1088
+ * Context of the resource that owns the task.
1089
+ * When the context is disposed, the task is cancelled and cannot be scheduled again.
1090
+ */
1091
+ // TODO(dmaretskyi): We don't really need to pass ctx in here, since close will also signal dispose.
1092
+ open(ctx) {
1093
+ this.#ctx = ctx;
1094
+ }
1095
+ /**
1096
+ * Closes the task and waits for it to finish if it is running.
1097
+ */
1098
+ async close() {
1099
+ this.#ctx = void 0;
1100
+ await this.join();
1101
+ }
1102
+ [Symbol.asyncDispose]() {
1103
+ return this.close();
1104
+ }
1105
+ /**
1106
+ * Schedule the task to run asynchronously.
1107
+ */
1108
+ schedule() {
1109
+ if (!this.#ctx || this.#ctx.disposed) {
1110
+ throw new Error("AsyncTask not open");
1111
+ }
1112
+ if (this.#scheduled) {
1113
+ return;
1114
+ }
1115
+ scheduleTask(this.#ctx, async () => {
1116
+ await this.#currentTask;
1117
+ if (!this.#ctx || this.#ctx.disposed) {
1118
+ return;
1119
+ }
1120
+ this.#scheduled = false;
1121
+ const completionTrigger = this.#nextTask;
1122
+ this.#nextTask = new Trigger();
1123
+ this.#currentTask = runInContextAsync(this.#ctx, () => this.#callback()).then(() => {
1124
+ completionTrigger.wake();
1125
+ });
1126
+ });
1127
+ this.#scheduled = true;
1128
+ }
1129
+ /**
1130
+ * Schedule the task to run and wait for it to finish.
1131
+ */
1132
+ async runBlocking() {
1133
+ if (this.#ctx?.disposed) {
1134
+ throw new ContextDisposedError2();
1135
+ }
1136
+ this.schedule();
1137
+ await this.#nextTask.wait();
1138
+ }
1139
+ /**
1140
+ * Waits for the current task to finish if it is running.
1141
+ * Does not schedule a new task.
1142
+ */
1143
+ async join() {
1144
+ await this.#currentTask;
1145
+ }
1146
+ };
1075
1147
  var runInContext = (ctx, fn) => {
1076
1148
  try {
1077
1149
  fn();
@@ -1594,6 +1666,7 @@ var UpdateScheduler = class {
1594
1666
  }
1595
1667
  };
1596
1668
  export {
1669
+ AsyncTask,
1597
1670
  CancellableObservableProvider,
1598
1671
  DeferredTask,
1599
1672
  Event,