harmony 鸿蒙Unsubscribing from Common Events in Dynamic Mode

  • 2025-06-06
  • 浏览 (6)

Unsubscribing from Common Events in Dynamic Mode

When to Use

After a service is finished in the dynamic mode, the subscriber should proactively unsubscribe from the event. You can call unsubscribe() to unsubscribe from a common event that is no longer required.

Available APIs

API Description
unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) Unsubscribes from a common event.

How to Develop

  1. Import the commonEventManager module.
   import { BusinessError, commonEventManager } from '@kit.BasicServicesKit';
   import { hilog } from '@kit.PerformanceAnalysisKit';

   const TAG: string = 'ProcessModel';
   const DOMAIN_NUMBER: number = 0xFF00;
  1. Subscribe to an event by following the procedure described in Subscribing to Common Events in Dynamic Mode.

  2. Call unsubscribe() in CommonEvent to unsubscribe from an event.

   // The subscriber object is created during event subscription.
   if (subscriber !== null) {
     commonEventManager.unsubscribe(subscriber, (err: BusinessError) => {
       if (err) {
         hilog.error(DOMAIN_NUMBER, TAG, `UnsubscribeCallBack err = ${JSON.stringify(err)}`);
       } else {
         hilog.info(DOMAIN_NUMBER, TAG, `Unsubscribe success`);
         subscriber = null;
       }
     })
   }

你可能感兴趣的鸿蒙文章

harmony 鸿蒙Process and Thread Communication

harmony 鸿蒙Introduction to Common Events

harmony 鸿蒙Publishing Common Events

harmony 鸿蒙Removing Sticky Common Events (for System Applications Only)

harmony 鸿蒙Subscribing to Common Events in Static Mode (for System Applications Only)

harmony 鸿蒙Common Event Subscription Overview

harmony 鸿蒙Subscribing to Common Events in Dynamic Mode

harmony 鸿蒙Using Emitter for Inter-Thread Communication

harmony 鸿蒙Publishing Common Events in C

harmony 鸿蒙Subscribing to Common Events in C

0  赞