代码拉取完成,页面将自动刷新
同步操作将从 OpenHarmony-SIG/LiveEventBus 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
LiveEventBus是一款消息总线,具有生命周期感知能力,支持Sticky,支持跨进程,支持跨APP发送消息。
ohpm install @ohos/liveeventbus
OpenHarmony ohpm 环境配置等更多内容,请参考如何安装 OpenHarmony ohpm 包
在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);
}
});
LiveEventBus
.get<string>("name")
.observeForever(observer);
LiveEventBus
.get("some_key")
.post(some_value);
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")));
更多详细用法请参考开源库Demo页面的实现
import { LiveEventBus } from '@ohos/liveeventbus'
LiveEventBus.get("key").post()
LiveEventBus.get("key").postAcrossApp()
LiveEventBus.get("key").postDelay()
LiveEventBus.get("key").broadcast()
LiveEventBus.get("key").observe()
LiveEventBus.get("key").observeSticky()
LiveEventBus.get("key").observeForever()
LiveEventBus.get("key").observeStickyForever()
LiveEventBus.get("key").removeObserver()
在下述版本验证通过:
DevEco Studio: 3.1 Beta2(3.1.0.400), SDK: API9 Release(3.2.11.9)
|---- LiveEventBus
| |---- entry # 示例代码文件夹
| |---- LiveEventBus # LiveEventBus库文件夹
| |---- index.ets # 对外接口
| └─src/main/ets/liveeventbus
| ├─core # 核心代码,事件总线处理类等
| ├─lifecycle # 生命周期数据处理
| ├─logger # 日志打印处理
| └─tslivedata # ts版livedata
|
|---- README.md # 安装使用方法
使用过程中发现任何问题都可以提 Issue 给我们,当然,我们也非常欢迎你给我们发 PR 。
本项目基于 Apache License 2.0 ,请自由地享受和参与开源。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。