Using emitter to implement hot start page jump

Read the original article:Using emitter to implement hot start page jump

Using emitter to implement hot start page jump

Problem Description

When opening the app via a card, the app cannot directly navigate to the specified page.

Attempts and results:

  1. Storing NavPathStack in a global variable — ineffective.
  2. Saving the target page, navigating first to the homepage via the router, and then checking on the homepage whether to navigate — works but causes an extra navigation, which does not fully meet requirements.

Background Knowledge

  • The Navigation component is used for page transitions between pages and within components. It supports:
    • Passing navigation parameters between components.
    • Flexible stack operations.
  • To enable communication between pages, the @ohos.events.emitter module provides:
    • Event sending and handling.
    • Continuous subscription, one-time subscription, cancellation.
    • Sending events to the event queue.

Solution

  1. Use the homepage as the root page for navigation. It is not destroyed and contains the NavPathStack variable.
  2. Publish events within the page lifecycle methods to notify the homepage.
  3. The homepage listens for these events and performs page navigation operations.
  4. Ensure correct page stack management during hot start.

Hot start: sending events via eventHub in onNewWant:

onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void {
  this.context.eventHub.emit('navigation', want.parameters?.path?.toString());
}

Homepage monitoring code (using router as NavPathStack instance):

getContext(this).eventHub.on('navigation', (path: string) => {
  let paths = this.router.getAllPathName();
  if (paths.slice().pop() === path) {
    return;
  }
  this.router.pushPath({ name: path }, false);
});

Rendering and navigation behavior:

  1. Cold start SingletonAbility, directly navigate to secondary page b (child page).
  2. Return to root page, open A child page, return to EntryAbility → triggers hot start.
  3. Hot start can still directly navigate to b child page, with page stack from top to bottom: b, a, root.

Verification Result

cke_1153.png

  • Navigation works correctly during hot start.
  • The page stack is preserved properly.
  • Direct navigation to the target child page is achieved without extra navigation steps.

Related Documents or Links

https://developer.huawei.com/consumer/en/doc/harmonyos-references/js-apis-emitter

https://developer.huawei.com/consumer/en/doc/harmonyos-guides/arkts-navigation-navigation

Written by Emine Inan

Leave a Reply