【OpenHarmony】消息总线:LiveEventBus

137 阅读3分钟

简介

LiveEventBus是一款消息总线,具有生命周期感知能力,支持Sticky,支持跨进程,支持跨APP发送消息。

下载安装

ohpm install @ohos/liveeventbus 

使用说明

在pages页面中使用

//引入
import { LiveEventBus,Lifecycle,MState } from '@ohos/liveeventbus'
import router from '@system.router';

const KEY_TEST_CLOSE_ALL_PAGE = "key_test_close_all_page";
@Entry
@Component
struct Demo {
 private mLifecycle: Lifecycle;
 aboutToAppear() {
  //创建生命周期感知对象
  this.mLifecycle = new Lifecycle(MState.STARTED)
  //订阅消息
  LiveEventBus
      .get<boolean>(KEY_TEST_CLOSE_ALL_PAGE)
      .observe(this, {
        onChanged(b:boolean) {
          if (b) {
            router.clear()
            router.back()
          }
        }
      });
 }
 build() {
    Column({ space: 10 }) {
      Text('LiveEventBus Demo')
        .fontSize(30)
        .fontWeight(FontWeight.Bold)
      Scroll() {
        Column({ space: 5 }) {
         Button('关闭All').onClick(event => {
            this.closeAll()
          })
        }
       }
     }
   }

 closeAll() {
    //发送消息
    LiveEventBus.get(KEY_TEST_CLOSE_ALL_PAGE).post(true);
  }

 aboutToDisappear() {
    destroyService()
    this.mLifecycle.markState(MState.DESTROYED)
  }

 //生命周期感知对象
 getLifecycle(): Lifecycle{
    return this.mLifecycle
  }
}

订阅消息

  • 以生命周期感知模式订阅消息
    LiveEventBus
      .get<string>("name")
      .observe(this, {
        onChanged(s) {
          showToast(s);
        }
      });
  • 以Forever模式订阅消息
 LiveEventBus
    .get<string>("name")
    .observeForever(observer);

发送消息

  • 不定义消息直接发送
LiveEventBus
	.get("some_key")
	.post(some_value);

DD一下:欢迎大家关注工粽号<程序猿百晓生>,可以了解到以下知识点。

`欢迎大家关注工粽号<程序猿百晓生>,可以了解到以下知识点。`
1.OpenHarmony开发基础
2.OpenHarmony北向开发环境搭建
3.鸿蒙南向开发环境的搭建
4.鸿蒙生态应用开发白皮书V2.0 & V3.0
5.鸿蒙开发面试真题(含参考答案) 
6.TypeScript入门学习手册
7.OpenHarmony 经典面试题(含参考答案)
8.OpenHarmony设备开发入门【最新版】
9.沉浸式剖析OpenHarmony源代码
10.系统定制指南
11.【OpenHarmony】Uboot 驱动加载流程
12.OpenHarmony构建系统--GN与子系统、部件、模块详解
13.ohos开机init启动流程
14.鸿蒙版性能优化指南
.......
  • 发送消息给ObserveForver注册的订阅者
LiveEventBus.get(KEY_TEST_OBSERVE_FOREVER)
      .post("Message To ForeverObserver: " + nextInt(100));
  • 进程内发送消息
    post(value: T): void
  • App之间发送消息
postAcrossProcess(value: T): void
  • 延迟发送
postOrderly(value: T): void
  • 延迟发送带生命周期
postDelay(value: T, delay: number, sender?: LifecycleOwner): void
  • 以广播形式发送消息
    broadcast(value: T): void
  • 先定义消息,再发送消息
    class DemoEvent {
      content: string

      constructor(content: string) {
        this.content = content
      }
    }

    LiveEventBus
          .get<string>('DemoEvent')
          .post(JSON.stringify(new DemoEvent("Hello world")));

接口说明

import { LiveEventBus } from '@ohos/liveeventbus'

  1. 进程内发送消息 LiveEventBus.get("key").post()
  2. App之间发送消息 LiveEventBus.get("key").postAcrossApp()
  3. 进程内发送消息,延迟发送,带生命周期 LiveEventBus.get("key").postDelay()
  4. 以广播的形式发送一个消息 LiveEventBus.get("key").broadcast()
  5. 注册一个Observer,生命周期感知,自动取消订阅 LiveEventBus.get("key").observe()
  6. 注册一个Observer,如果之前有消息发送,可以在注册时收到消息(消息同步) LiveEventBus.get("key").observeSticky()
  7. 注册一个Observer,需手动解除绑定 LiveEventBus.get("key").observeForever()
  8. 注册一个Observer,如果之前有消息发送,可以在注册时收到消息(消息同步) LiveEventBus.get("key").observeStickyForever()
  9. 通过observeForever或observeStickyForever注册的,需要调用该方法取消订阅 LiveEventBus.get("key").removeObserver()
  10. 取消App之间的消息订阅 LiveEventBus.get("key").unsubscribe()

目录结构

|---- LiveEventBus  
|     |---- entry  # 示例代码文件夹
|     |---- library  # LiveEventBus库文件夹
|           |---- index.ts  # 对外接口
|           └─src/main/ets/LiveEventBus
|                          ├─core # 核心代码,事件总线处理类等
|                          ├─lifecycle # 生命周期数据处理
|                          ├─logger # 日志打印处理
|                          └─tslivedata # ts版livedata
|                 |---- GlobalContext  # GlobalContext替代globalThis配置
|                 |---- LiveEventBus  # LiveEventBus核心类
|---- README.md  # 安装使用方法    
|---- README_zh.md  # 安装使用方法