类 Lifecycle 接口的生命周期监听和注册以及 ViewModel 管理
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(() => {
//...
})
}
}