ActiveData在HarmonyOS中的原理分析及应用我们先来了解一下Lifecycle和DataObserver这两个重要的类,它们在ActiveData的整个运行中起着非常重要的作用。Lifecycle提供了观察Ability和AbilitySlice生命周期的能力。DataObserver通过持有一个Lifecycle对象来观察Ability或AbilitySlice的生命周期变化。同时DataObserver也让ActiveData可以观察到它的生命周期变化。所以DataObserver和ActiveData相互观察,DataObserver观察ActiveData。数据变化,ActiveData观察DataObserver的生命周期变化。ActiveData的功能和特点ActiveData是一个数据通知组件,具有感知生命周期变化的能力。非常适合在一些数据同步性比较高的场景下使用。它具有以下三个特点。基于观察者模式:ActiveData是一个保存可观察数据的类。ActiveData需要一个观察者对象,一般是DataObserver类的具体实现。生命周期意识:ActiveData具有生命周期意识。目前ActiveData有两种通知方式,一种是当Ability/AbilitySlice的生命周期处于活跃状态(ACTIVE)时更新数据,另一种是当Ability/AbilitySlice的生命周期处于任意存活状态时更新数据。状态(即只要它没有被破坏)就可以更新数据。自动取消数据订阅:ActiveData必须与实现了Lifecycle的对象一起使用。当Ability/AbilitySlice被销毁时(STOP状态),会自动取消订阅,一定程度上可以避免内存泄露等问题。实践一、基本用法{super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);activeData=newActiveData<>();dataObserver.setLifecycle(getLifecycle());mText=(Text)findComponentById(ResourceTable.Id_text_helloworld);subscribe();}privatevoidsubscribe(){activeData.addObserver(dataObserver,true);}@OverridepublicvoidonActive(){super.onActive();activeData.setData("NewHelloWorld");}}运行后截图:从运行结果可以看出,setData调用后会立即触发onChanged回调方法2.主线程手动调用//添加如下代码测试DataObserver的onChanged方法是否会执行findComponentById(ResourceTable.Id_button).setClickedListener(component->activeData.setData("ILoveChina"));运行结果如下:从运行结果可以看出,onChanged方法会一直触发,因为值相同,所以不会执行,虽然暂时看不到鸿蒙源代码,但我们可以大胆猜测,鸿蒙底层维护着一个类似于版本号的标记。每设置一次setData,标记就会自动+1,从而通过这个版本号来判断数据是否发生变化,进而决定是否触发onChanged回调方法3.子线程调用@OverridepublicvoidonActive(){super.onActive();newThread(()->activeData.setData("NewHelloWorld")).start();}4、运行后没有问题,可以正常调用。setData方法可以在子线程中调用。publicclassMainAbilitySliceextendsAbilitySlice{privateActiveDataactiveData;privateActiveDataactiveData2;privateTextmText;privatefinalDataObserverdataObserver=newDataObserver(){@OverridepublicvoidonChanged(字符串){mText.setText(s);System.out.println("ActiveData:---onChange:"+s);}};privatefinalDataObserverdataObserver2=newDataObserver(){@OverridepublicvoidonChanged(Strings){mText.setText(s);System.out.println("ActiveData:---onChange:"+s);}};@OverridepublicvoidonStart(Intentintent){super.onStart(intent);super.setUIContent(ResourceTable.Layout_ability_main);activeData=newActiveData<>();activeData2=newActiveData<>();dataObserver.setLifecycle(getLifecycle());dataObserver2.setLifecycle(getLifecycle());mText=(Text)findComponentById(ResourceTable.Id_text_helloworld);findComponentById(ResourceTable.Id_button).setClickedListener(组件->activeData.setData("ILoveChina"));findComponentById(ResourceTable.Id_addObserver_true).setClickedListener(component->{System.out.println("ActiveData:------------");Intentintent1=newIntent();Operationoperation=newIntent.OperationBuilder().withDeviceId("").withBundleName(getBundleName()).withAbilityName(SecondAbility.class.getName()).build();intent1.setOperation(operation);startAbility(intent1);//这里是为了验证Ability在inActive状态的值的变化情况newEventHandler(EventRunner.getMainEventRunner()).postTask(()->activeData.setData("NewHelloWorld"),2000);});findComponentById(ResourceTable.Id_addObserver_false).setClickedListener(component->{System.out.println("ActiveData:------------");Intentintent1=newIntent();Operationoperation=newIntent.OperationBuilder().withDeviceId("").withBundleName(getBundleName()).withAbilityName(SecondAbility.class.getName()).build();intent1.setOperation(operation);startAbility(intent1);//这里是验证inActive状态下Ability值的变化newEventHandler(EventRunner.getMainEventRunner()).postTask(()->activeData2.setData("NewHelloWorld"),2000);});subscribe();}privatevoidsubscribe(){activeData.addObserver(dataObserver,true);activeData2.addObserver(dataObserver,false);}@OverridepublicvoidonActive(){super.onActive();System.out.println("ActiveData:---onActive");}@OverrideprotectedvoidonInactive(){super.onInactive();System.out.println("ActiveData:---onInactive");}@OverrideprotectedvoidonBackground(){super.onBackground();System.出去。println("ActiveData:---onBackground");}@OverridepublicvoidonForeground(Intentintent){super.onForeground(intent);System.out.println("ActiveData:---onForeground");}}运行效果如下如下:从上面的运行结果可以看出addObserver(dataObserver,true/false)方法的特点。当为true时,表示无论在任何生命周期中Ability/AbilitySlice的状态如何,都会触发onChanged回调方法。当为false时,表示Ability/AbilitySlice只在状态为ACTIVE时才会触发onChanged方法综上所述,ActiveData依靠Lifecycle来感知组件的生命周期,从而避免内部泄露。开发者不需要维护观察者对象。当Ability/AbilitySlice被销毁时,关联的观察者将被自动移除。当Ability/AbilitySlice处于活动(ACTIVE)状态时,当ActiveData数据源发生变化时,会立即触发onChanged方法来更新UI或执行我们想要的任何操作。setData方法可以在任何线程中调用,开发者无需关心调用者是否是主线程中的setData方法,即使设置了相同的数据对象,onChanged方法依然会被触发。更多信息请访问:与华为官方共建的鸿蒙技术社区https://harmonyos.51cto.com