类 Lifecycle 接口的生命周期监听和注册以及 ViewModel 管理
已支持 Navigation
ohpm install @gargantua7/lifecycle
继承LifecycleAbility
export default class EntryAbility extends LifecycleAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
super.onCreate(want, launchParam)
}
onDestroy(): void {
super.onDestroy();
}
}或者在已有Ability中调用注册方法
export default class EntryAbility extends UIAbilitiy {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
LifecycleAbility.register(this)
}
onDestroy(): void {
LifecycleAbility.unregister(this)
}
}同一个页面中无论何处获得的Lifecycle对象均为同一个
@ComponentV2
struct Component {
private lifecycle!: Lifecycle
aboutToAppear(): void {
this.lifecycle = Lifecycle.getOrCreate(this)
}
}this.lifecycle.addObserver({
onStateChanged: (state) => {
promptAction.showToast({
message: "onStateChanged " + state
})
}
} as LifecycleEventObserver)this.lifecycle.addObserver({
aboutToAppear: () => { ... },
aboutToDisappear: () => { ... },
onPageShow: () => { ... },
onPageHide: () => { ... },
onBackPress: () => { ... },
} as DefaultLifecycleObserver)在同一个页面中无论何处获得相同类型同名的ViewModel实例对象均为同一个
@ComponentV2
struct Component {
get viewModel() {
ViewModelProvider.of(this).get(MyViewModel [, "viewModelName"])
}
}
class MyViewModel extends ViewModel {
}将实现 Closeable的对象添加到ViewModel中,ViewModel被 clear 时将自动调用 Closeable 的 close 方法
class MyViewModel extends ViewModel {
init() {
this.addCloseable({
close() {
// ...
}
})
}
}提供LifecycleScope和ViewModelScope
两者均仅在页面生命周期在onPageShow时才运行提交的任务,在onPageHide时暂停执行还未执行的任务,在对应的组件生命周期结束后停止执行还未执行的任务
@ComponentV2
struct Component {
aboutToAppear(): void {
Lifecycle.getOrCreate(this).lifecycleScope.launch(() => {
//...
})
}
}class MyViewModel extends ViewModel {
init() {
this.viewModelScope.launch(() => {
//...
})
}
}Lifecycle.getOrCreate 会自动识别是否在 NavDestination 中,其余 API 保持不变
提供 registerComponentIntoLifecycle 方法用于回调原 router 方式中存在但 Navigation 方式不存在的 onPageShow 以及 onPageHide 等方法
@ComponentV2
struct Component {
aboutToAppear(): void {
registerComponentIntoLifecycle(this)
}
onPageShow(): void {}
onPageHide(): void {}
}