Skip to content

Commit

Permalink
add objectwait module
Browse files Browse the repository at this point in the history
  • Loading branch information
Alistairot committed Dec 18, 2023
1 parent e764c56 commit 6ba5440
Show file tree
Hide file tree
Showing 14 changed files with 379 additions and 25 deletions.
47 changes: 45 additions & 2 deletions dist/moye.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -604,8 +604,8 @@ export declare class EventCom extends Entity {
* @param handler
* @param entity
*/
subscribe(eventCode: number, handler: Function, entity: Entity): void;
publish(eventCode: number, ...args: any[]): void;
subscribe(eventType: string, handler: Function, entity: Entity): void;
publish(eventType: string, ...args: any[]): void;
}
export interface IColorLike {
r: number;
Expand Down Expand Up @@ -4298,6 +4298,49 @@ export declare class MoyeAssets extends Singleton {
static releaseBundle(bundleAsset: BundleAsset): void;
static unloadUnusedAssets(): void;
}
export declare enum WaitError {
SUCCESS = 0,
DESTROY = 1,
CANCEL = 2,
TIMEOUT = 3
}
export declare class AWait extends RecycleObj {
error: WaitError;
}
export declare class ObjectWait extends Entity {
private _tasks;
protected destroy(): void;
/**
* 一直等待 知道notify了 永不超时
* @param type
* @param cancellationToken
* @returns
*/
wait<T extends AWait>(type: Type<T>, cancellationToken?: CancellationToken): Promise<T>;
/**
* 等待且有超时限制 超时将会取消等待
* @param type
* @param timeout ms
* @param cancellationToken
* @returns
*/
waitWithTimeout<T extends AWait>(type: Type<T>, timeout: number, cancellationToken?: CancellationToken): Promise<T>;
/**
* 取消上一个等待
* @param type
*/
private cancelLastWait;
/**
* 超时取消等待
* @param type
* @param time
* @param cancellationToken
* @returns
*/
private timeoutRun;
private createWaitInstance;
notify<T extends AWait>(obj: T): void;
}
/**
* button async listener
* wait for the callback to complete
Expand Down
2 changes: 1 addition & 1 deletion dist/moye.min.mjs

Large diffs are not rendered by default.

151 changes: 141 additions & 10 deletions dist/moye.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1873,11 +1873,11 @@ class EventAutoReleaseCom extends Entity {
destroy() {
const eventMap = this.eventCom['eventMap'];
for (const item of this.events) {
const eventSet = eventMap.get(item.eventCode);
const eventSet = eventMap.get(item.eventType);
eventSet.delete(item);
item.entity = null;
item.handler = null;
item.eventCode = null;
item.eventType = null;
item.dispose();
}
this.events = null;
Expand All @@ -1903,7 +1903,7 @@ class EventCom extends Entity {
for (const item of eventSet) {
item.entity = null;
item.handler = null;
item.eventCode = null;
item.eventType = null;
item.dispose();
}
eventSet.clear();
Expand All @@ -1917,16 +1917,16 @@ class EventCom extends Entity {
* @param handler
* @param entity
*/
subscribe(eventCode, handler, entity) {
subscribe(eventType, handler, entity) {
const item = EventItem.create({
entity: entity,
handler: handler,
eventCode: eventCode
eventType: eventType
});
let eventSet = this._eventMap.get(eventCode);
let eventSet = this._eventMap.get(eventType);
if (!eventSet) {
eventSet = new Set();
this._eventMap.set(eventCode, eventSet);
this._eventMap.set(eventType, eventSet);
}
eventSet.add(item);
let autoReleaseCom = entity.getCom(EventAutoReleaseCom);
Expand All @@ -1936,8 +1936,8 @@ class EventCom extends Entity {
}
autoReleaseCom.addItem(item);
}
publish(eventCode, ...args) {
const eventSet = this._eventMap.get(eventCode);
publish(eventType, ...args) {
const eventSet = this._eventMap.get(eventType);
if (eventSet) {
for (const item of eventSet) {
item.handler.apply(item.entity, args);
Expand Down Expand Up @@ -11112,6 +11112,137 @@ AfterProgramInitHandler = __decorate$5([
EventDecorator(AfterProgramInit, SceneType.NONE)
], AfterProgramInitHandler);

var WaitError;
(function (WaitError) {
WaitError[WaitError["SUCCESS"] = 0] = "SUCCESS";
WaitError[WaitError["DESTROY"] = 1] = "DESTROY";
WaitError[WaitError["CANCEL"] = 2] = "CANCEL";
WaitError[WaitError["TIMEOUT"] = 3] = "TIMEOUT";
})(WaitError || (WaitError = {}));

class AWait extends RecycleObj {
constructor() {
super(...arguments);
this.error = WaitError.SUCCESS;
}
}

class ObjectWait extends Entity {
constructor() {
super(...arguments);
this._tasks = new Map;
}
destroy() {
for (const [type, task] of this._tasks) {
const obj = this.createWaitInstance(type, WaitError.DESTROY);
this.notify(obj);
}
}
/**
* 一直等待 知道notify了 永不超时
* @param type
* @param cancellationToken
* @returns
*/
async wait(type, cancellationToken) {
this.cancelLastWait(type);
const tcs = Task.create(type);
this._tasks.set(type, tcs);
let cancelAction;
let ret;
if (cancellationToken) {
cancelAction = () => {
const obj = this.createWaitInstance(type, WaitError.CANCEL);
this.notify(obj);
};
cancellationToken.add(cancelAction);
}
try {
ret = await tcs;
}
finally {
cancellationToken?.remove(cancelAction);
cancelAction = null;
}
return ret;
}
/**
* 等待且有超时限制 超时将会取消等待
* @param type
* @param timeout ms
* @param cancellationToken
* @returns
*/
async waitWithTimeout(type, timeout, cancellationToken) {
this.cancelLastWait(type);
const tcs = Task.create(type);
this._tasks.set(type, tcs);
this.timeoutRun(type, timeout, cancellationToken);
let cancelAction;
let ret;
if (cancellationToken) {
cancelAction = () => {
const obj = this.createWaitInstance(type, WaitError.CANCEL);
this.notify(obj);
};
cancellationToken.add(cancelAction);
}
try {
ret = await tcs;
}
finally {
cancellationToken?.remove(cancelAction);
cancelAction = null;
}
return ret;
}
/**
* 取消上一个等待
* @param type
*/
cancelLastWait(type) {
if (!this._tasks.has(type)) {
return;
}
coreWarn('上一个wait已经取消, {0}', type.name);
const obj = this.createWaitInstance(type, WaitError.CANCEL);
this.notify(obj);
}
/**
* 超时取消等待
* @param type
* @param time
* @param cancellationToken
* @returns
*/
async timeoutRun(type, time, cancellationToken) {
await TimerMgr.get().waitAsync(time, cancellationToken);
if (cancellationToken?.isCancel()) {
return;
}
// 已经执行完毕 不需要执行超时的逻辑
if (!this._tasks.has(type)) {
return;
}
const obj = this.createWaitInstance(type, WaitError.TIMEOUT);
this.notify(obj);
}
createWaitInstance(type, error) {
const obj = type.create();
obj.error = error;
return obj;
}
notify(obj) {
const tcs = this._tasks.get(obj.constructor);
if (!tcs) {
return;
}
this._tasks.delete(obj.constructor);
tcs.setResult(obj);
obj.dispose();
}
}

/**
* button async listener
* wait for the callback to complete
Expand Down Expand Up @@ -13013,4 +13144,4 @@ class YYJJoystickListener extends Entity {
}
}

export { AEvent, AEventHandler, AMoyeView, AffineTransform, AfterCreateClientScene, AfterCreateCurrentScene, AfterProgramInit, AfterProgramStart, AfterSingletonAdd, AssetOperationHandle, AsyncButtonListener, BeforeProgramInit, BeforeProgramStart, BeforeSingletonAdd, BundleAsset, CTWidget, CancellationToken, CancellationTokenTag, Color, CoroutineLock, CoroutineLockItem, CoroutineLockTag, DecoratorCollector, EPSILON, Entity, EntityCenter, EventCom, EventDecorator, EventDecoratorType, EventHandlerTag, EventSystem, Game, HALF_PI, IdGenerator, IdStruct, InstanceIdStruct, JsHelper, Logger, Mat3, Mat4, MoyeAssets, MoyeViewMgr, ObjectPool, Options, Program, Quat, Rect, RecycleObj, Root, RoundBoxSprite, Scene, SceneFactory, SceneRefCom, SceneType, Singleton, Size, SizeFollow, SpeedType, TWO_PI, Task, TimeHelper, TimeInfo, TimerMgr, Vec2, Vec3, Vec4, ViewDecorator, ViewDecoratorType, ViewLayer, YYJJoystick, YYJJoystickCom, YYJJoystickListener, YYJJoystickMoveEvent, YYJJoystickSpeedChangeEvent, absMax, absMaxComponent, approx, bits, clamp, clamp01, color, enumerableProps, equals, error, floatToHalf, halfToFloat, inverseLerp, lerp, log, mat4, nextPow2, pingPong, preTransforms, pseudoRandom, pseudoRandomRange, pseudoRandomRangeInt, quat, random, randomRange, randomRangeInt, rect, repeat, safeCall, setRandGenerator, size, toDegree, toRadian, v2, v3, v4, warn };
export { AEvent, AEventHandler, AMoyeView, AWait, AffineTransform, AfterCreateClientScene, AfterCreateCurrentScene, AfterProgramInit, AfterProgramStart, AfterSingletonAdd, AssetOperationHandle, AsyncButtonListener, BeforeProgramInit, BeforeProgramStart, BeforeSingletonAdd, BundleAsset, CTWidget, CancellationToken, CancellationTokenTag, Color, CoroutineLock, CoroutineLockItem, CoroutineLockTag, DecoratorCollector, EPSILON, Entity, EntityCenter, EventCom, EventDecorator, EventDecoratorType, EventHandlerTag, EventSystem, Game, HALF_PI, IdGenerator, IdStruct, InstanceIdStruct, JsHelper, Logger, Mat3, Mat4, MoyeAssets, MoyeViewMgr, ObjectPool, ObjectWait, Options, Program, Quat, Rect, RecycleObj, Root, RoundBoxSprite, Scene, SceneFactory, SceneRefCom, SceneType, Singleton, Size, SizeFollow, SpeedType, TWO_PI, Task, TimeHelper, TimeInfo, TimerMgr, Vec2, Vec3, Vec4, ViewDecorator, ViewDecoratorType, ViewLayer, WaitError, YYJJoystick, YYJJoystickCom, YYJJoystickListener, YYJJoystickMoveEvent, YYJJoystickSpeedChangeEvent, absMax, absMaxComponent, approx, bits, clamp, clamp01, color, enumerableProps, equals, error, floatToHalf, halfToFloat, inverseLerp, lerp, log, mat4, nextPow2, pingPong, preTransforms, pseudoRandom, pseudoRandomRange, pseudoRandomRangeInt, quat, random, randomRange, randomRangeInt, rect, repeat, safeCall, setRandGenerator, size, toDegree, toRadian, v2, v3, v4, warn };
4 changes: 4 additions & 0 deletions gulp/modules.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ dynamic event component
[export=true]
资源管理

[name=ObjectWait]
[export=true]
wait something to be done

[name=AsyncExt]
[export=true]
async extension
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "moye-client",
"version": "1.0.2",
"version": "1.0.3",
"description": "game framework of cocos creator & nodejs",
"main": "dist/moye.mjs",
"types": "dist/moye.d.ts",
Expand Down
4 changes: 2 additions & 2 deletions src/EventCom/EventAutoReleaseCom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ export class EventAutoReleaseCom extends Entity {
const eventMap = this.eventCom['eventMap'];

for (const item of this.events) {
const eventSet = eventMap.get(item.eventCode);
const eventSet = eventMap.get(item.eventType);

eventSet.delete(item);
item.entity = null;
item.handler = null;
item.eventCode = null;
item.eventType = null;
item.dispose();
}

Expand Down
16 changes: 8 additions & 8 deletions src/EventCom/EventCom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ import { EventItem } from "./EventItem";
* 不允许取消订阅
*/
export class EventCom extends Entity {
private _eventMap: Map<number, Set<EventItem>> = new Map;
private _eventMap: Map<string, Set<EventItem>> = new Map;
protected destroy(): void {
const eventMap = this._eventMap;

for (const eventSet of eventMap.values()) {
for (const item of eventSet) {
item.entity = null;
item.handler = null;
item.eventCode = null;
item.eventType = null;
item.dispose();
}

Expand All @@ -31,18 +31,18 @@ export class EventCom extends Entity {
* @param handler
* @param entity
*/
subscribe(eventCode: number, handler: Function, entity: Entity) {
subscribe(eventType: string, handler: Function, entity: Entity) {
const item = EventItem.create({
entity: entity,
handler: handler,
eventCode: eventCode
eventType: eventType
});

let eventSet = this._eventMap.get(eventCode);
let eventSet = this._eventMap.get(eventType);

if (!eventSet) {
eventSet = new Set();
this._eventMap.set(eventCode, eventSet);
this._eventMap.set(eventType, eventSet);
}

eventSet.add(item);
Expand All @@ -57,8 +57,8 @@ export class EventCom extends Entity {
autoReleaseCom.addItem(item);
}

publish(eventCode: number, ...args: any[]) {
const eventSet = this._eventMap.get(eventCode);
publish(eventType: string, ...args: any[]) {
const eventSet = this._eventMap.get(eventType);

if (eventSet) {
for (const item of eventSet) {
Expand Down
2 changes: 1 addition & 1 deletion src/EventCom/EventItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ import { Entity, RecycleObj } from "../Core/Core";
export class EventItem extends RecycleObj {
entity: Entity;
handler: Function;
eventCode: number;
eventType: string;
}
6 changes: 6 additions & 0 deletions src/ObjectWait/AWait.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { RecycleObj } from "../Core/Core";
import { WaitError } from "./WaitError";

export class AWait extends RecycleObj {
error: WaitError = WaitError.SUCCESS;
}
3 changes: 3 additions & 0 deletions src/ObjectWait/Index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './WaitError';
export * from './AWait';
export * from './ObjectWait';
Loading

0 comments on commit 6ba5440

Please sign in to comment.