鸿蒙NEXT开发Emitter工具类(ArkTs)

发布于:2025-04-12 ⋅ 阅读:(160) ⋅ 点赞:(0)
import { emitter } from '@kit.BasicServicesKit';

/**
 * TODO Emitter工具类(进行线程间通信)
 * author: 鸿蒙布道师
 * since: 2025/04/11
 */
export class EmitterUtil {
  /**
   * 发送事件
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @param eventData 发送的数据
   * @param priority 事件被发送的优先级,默认为 HIGH。
   */
  static post<T>(
    eventId: string | number,
    eventData: T,
    priority: emitter.EventPriority = emitter.EventPriority.HIGH
  ) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    const options: emitter.Options = { priority };
    emitter.emit(eventId.toString(), options, { data: eventData });
  }

  /**
   * 订阅事件
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @param callback 接收到该事件时需要执行的回调处理函数。
   */
  static on<T>(eventId: string | number, callback: Callback<T>) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    emitter.on(eventId.toString(), (eventData: emitter.GenericEventData<T>) => {
      if (eventData.data) {
        callback(eventData.data); // 确保 data 不为 undefined
      } else {
        console.warn('Received undefined data for event:', eventId);
      }
    });
  }

  /**
   * 单次订阅指定事件
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @param callback 接收到该事件时需要执行的回调处理函数。
   */
  static once<T>(eventId: string | number, callback: Callback<T>) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    emitter.once(eventId.toString(), (eventData: emitter.GenericEventData<T>) => {
      if (eventData.data) {
        callback(eventData.data); // 确保 data 不为 undefined
      } else {
        console.warn('Received undefined data for event:', eventId);
      }
    });
  }

  /**
   * 取消事件订阅
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   */
  static unsubscribe(eventId: string | number) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    emitter.off(eventId.toString());
  }

  /**
   * 获取指定事件的订阅数
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @returns 订阅数
   */
  static getListenerCount(eventId: string | number): number {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    return emitter.getListenerCount(eventId.toString());
  }

  /**
   * 取消指定事件的特定回调
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @param callback 要取消的回调函数。
   */
  static off<T>(eventId: string | number, callback: Callback<emitter.GenericEventData<T>>) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    emitter.off(eventId.toString(), callback);
  }
}

// 定义通用回调类型
type Callback<T> = (data: T) => void;

代码如下:
import { emitter } from '@kit.BasicServicesKit';

/**
 * TODO Emitter工具类(进行线程间通信)
 * author: 鸿蒙布道师
 * since: 2025/04/11
 */
export class EmitterUtil {
  /**
   * 发送事件
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @param eventData 发送的数据
   * @param priority 事件被发送的优先级,默认为 HIGH。
   */
  static post<T>(
    eventId: string | number,
    eventData: T,
    priority: emitter.EventPriority = emitter.EventPriority.HIGH
  ) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    const options: emitter.Options = { priority };
    emitter.emit(eventId.toString(), options, { data: eventData });
  }

  /**
   * 订阅事件
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @param callback 接收到该事件时需要执行的回调处理函数。
   */
  static on<T>(eventId: string | number, callback: Callback<T>) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    emitter.on(eventId.toString(), (eventData: emitter.GenericEventData<T>) => {
      if (eventData.data) {
        callback(eventData.data); // 确保 data 不为 undefined
      } else {
        console.warn('Received undefined data for event:', eventId);
      }
    });
  }

  /**
   * 单次订阅指定事件
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @param callback 接收到该事件时需要执行的回调处理函数。
   */
  static once<T>(eventId: string | number, callback: Callback<T>) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    emitter.once(eventId.toString(), (eventData: emitter.GenericEventData<T>) => {
      if (eventData.data) {
        callback(eventData.data); // 确保 data 不为 undefined
      } else {
        console.warn('Received undefined data for event:', eventId);
      }
    });
  }

  /**
   * 取消事件订阅
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   */
  static unsubscribe(eventId: string | number) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    emitter.off(eventId.toString());
  }

  /**
   * 获取指定事件的订阅数
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @returns 订阅数
   */
  static getListenerCount(eventId: string | number): number {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    return emitter.getListenerCount(eventId.toString());
  }

  /**
   * 取消指定事件的特定回调
   * @param eventId 事件ID,string类型的eventId不支持空字符串。
   * @param callback 要取消的回调函数。
   */
  static off<T>(eventId: string | number, callback: Callback<emitter.GenericEventData<T>>) {
    if (!eventId || (typeof eventId === 'string' && !eventId.trim())) {
      throw new Error('Event ID cannot be empty or null.');
    }
    emitter.off(eventId.toString(), callback);
  }
}

// 定义通用回调类型
type Callback<T> = (data: T) => void;

网站公告

今日签到

点亮在社区的每一天
去签到