线程通信
Emitter 和 commonEventManager 都支持线程通信,但不同的是 Emitter 只能在 APP 内
Emitter 定义介绍
bash
declare namespace emitter {
function on(event: InnerEvent, callback: Callback<EventData>): void;
function once(event: InnerEvent, callback: Callback<EventData>): void;
function off(eventId: number): void;
function emit(event: InnerEvent, data?: EventData): void;
}
on:开启订阅事件,event 表示订阅的具体事件,callbak 表示匹配到事件后的回调。
off:结束订阅事件,后续即使有事件也不再会回调。
once:只订阅一次事件,后续即使有事件也不再会回调。
emit:发布事件,event 表示订阅的具体事件,data 表示发布事件的额外参数。
Emitter 订阅事件
引入 emitter 包
bash
import { emitter } from '@kit.BasicServicesKit';
开启事件订阅
bash
emitter.on({
eventId: 10086, // 指定事件ID
priority: emitter.EventPriority.HIGH // 事件优先级
}, (data) => { // 事件回调
console.log("")
})
Emitter 发布事件
发布事件
bash
emitter.emit({
eventId: 10086, // 事件ID
priority: emitter.EventPriority.IMMEDIATE // 事件优先级
})
以上就是事件的订阅和发布用法,接下来我们举一个简单示例样式一下:
bash
import { emitter } from '@kit.BasicServicesKit';
@Entry @Component struct Index {
@State text: string = "";
private subscribe() {
emitter.on({ // 开启事件订阅
eventId: 10086, // 指定事件的ID
priority: emitter.EventPriority.IMMEDIATE // 事件的优先级
}, (data) => { // 事件回调
if(data) {
this.text = "data: " + JSON.stringify(data);
} else {
this.text = "none data";
}
})
this.text = "subscribe success";
}
private unsubscribe() {
emitter.off(10086); // 取消订阅事件
this.text = "unsubscribe success";
}
private publishEvent() {
emitter.emit({ // 发布事件
eventId: 10086, // 指定事件ID
priority: emitter.EventPriority.IMMEDIATE // 指定事件优先级
})
}
private publishEventWithData() {
emitter.emit({
eventId: 10086, // 发布事件
priority: emitter.EventPriority.IMMEDIATE // 指定事件优先级
}, { // 添加额外参数
data: {
"test": 'emitter test'
}
})
}
build() {
Column({space: 10}) {
Button("订阅事件")
.size({width: 260, height: 50})
.onClick(() => {
this.subscribe();
})
Button("取消订阅")
.size({width: 260, height: 50})
.onClick(() => {
this.unsubscribe();
})
Text(this.text)
.size({width: 260, height: 150})
.fontSize(22)
.backgroundColor("#dbdbdb")
Divider()
.size({width: 260, height: 5})
Button("发布事件")
.size({width: 260, height: 50})
.onClick(() => {
this.publishEvent();
})
Button("发布事件并携带参数")
.size({width: 260, height: 50})
.onClick(() => {
this.publishEventWithData();
})
}
.padding(10)
.size({width: "100%", height: '100%'})
}
}
样例很简单,首先订阅事件,在订阅事件时指定事件的 ID,然后开始订阅,当有匹配的事件时,会回调给订阅者,运行结果如下图所示: