原来的设置页只在打开时load,保存时save。只要所有修改都从同一页面发生,这个接口就够用。增加快捷设置入口以后,已经打开的页面却不知道仓储有了新值。播客偏好这一节把仓储从“按需读取”推进到“提交后通知”,同时保留上一节对编辑草稿的保护。

提交通知与订阅释放封面

一、从键变化走向业务提交快照

Preferences提供change等订阅能力,官方文档描述了键变化和flush触发通知的关系。一个PlaybackSettings却由speed和autoNext两个字段组成,界面需要的是完整业务快照,而不只是某一个键的名字。把键事件直接绑定到两个状态字段,容易让页面自己承担拼装、读取和顺序判断。

当前工程已经规定所有写入通过PodcastSettings,且在单进程内串行执行。因此这里选择仓储自己的提交通知:save的两个put与flush都成功后,发送本次完整副本。它不是新增SDK事件,也不声称能发现绕过仓储的写入;需要跨进程或外部写入感知时,应按实际存储方案重新设计。

失败不发布成功通知。flush失败时,调用者仍收到拒绝,页面保留草稿,订阅者也不会收到“已经提交”的快照。此前put可能已经改变内存,这仍不是事务回滚。通知描述本仓储确认成功的提交,不能把它扩张成任意时间读取缓存都必然等于最近一次成功提交。

读取接口向提交订阅接口的演进

二、先交付当前值,再按队列接收后续提交

新接口watch返回Promise,完成后得到释放函数。它与load、save进入同一个SerialQueue,在队列任务中读取当前值、注册回调并投递首个副本。这样调用者不必先load再subscribe,避免两步之间的提交漏过通知。

watch不能在队列任务里再调用公开load并等待,因为load还会重新排到同一队列后面,形成自己等待自己的问题。代码把读取实现抽到readCurrent,load和watch都在已取得队列执行资格后调用它。这是接口演进里最需要逐行检查的一处依赖关系。

下面完整代码替换entry/src/main/ets/data/PodcastSettings.ets。XML文件、speed范围、autoNext含义、schemaVersion迁移以及共享opening都沿用前文。继续面向API12及以上Stage工程,PC/2in1按对应API与设备支持条件配置,不新增应用权限。

import { preferences } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

export interface PlaybackSettings {
  speed: number;
  autoNext: boolean;
}

export function validSpeed(value: number): boolean {
  return Number.isFinite(value) && value >= 0.5 && value <= 2.0;
}

class SerialQueue {
  private tail: Promise<void> = Promise.resolve();

  enqueue<T>(task: () => Promise<T>): Promise<T> {
    const result: Promise<T> = this.tail.then(task);
    this.tail = result.then(() => {}, () => {});
    return result;
  }
}

export type SettingsListener = (value: PlaybackSettings) => void;
interface SettingsSubscription { id: number; listener: SettingsListener; }
export class PodcastSettings {
  private subscriptions: SettingsSubscription[] = [];
  private nextSubscriptionId: number = 0;

  private deliver(listener: SettingsListener, value: PlaybackSettings): void {
    try { listener({ speed: value.speed, autoNext: value.autoNext }); } catch (_) {}
  }
  private publish(value: PlaybackSettings): void {
    const current = this.subscriptions.slice();
    current.forEach((entry: SettingsSubscription) => {
      if (this.subscriptions.some((active: SettingsSubscription) => active.id === entry.id)) {
        this.deliver(entry.listener, value);
      }
    });
  }
  watch(listener: SettingsListener): Promise<() => void> {
    return this.queue.enqueue<() => void>(async () => {
      const value = await this.readCurrent();
      const id = ++this.nextSubscriptionId;
      this.subscriptions.push({ id, listener });
      this.deliver(listener, value);
      return () => {
        this.subscriptions = this.subscriptions.filter((entry: SettingsSubscription) => entry.id !== id);
      };
    });
  }

  private static opening: Promise<PodcastSettings> | undefined = undefined;
  private store: preferences.Preferences;
  private queue: SerialQueue = new SerialQueue();

  private constructor(store: preferences.Preferences) {
    this.store = store;
  }

  static open(context: common.UIAbilityContext): Promise<PodcastSettings> {
    const existing = PodcastSettings.opening;
    if (existing !== undefined) {
      return existing;
    }
    const created: Promise<PodcastSettings> = preferences.getPreferences(context, {
      name: 'podcast_settings'
    }).then(async (store: preferences.Preferences): Promise<PodcastSettings> => {
      const repository = new PodcastSettings(store);
      await repository.initialize();
      return repository;
    }).catch((error: BusinessError) => {
      PodcastSettings.opening = undefined;
      throw error;
    });
    PodcastSettings.opening = created;
    return created;
  }

  private initialize(): Promise<void> {
    return this.queue.enqueue<void>(async () => {
      const version = await this.store.get('schemaVersion', 0);
      if (typeof version !== 'number' || !Number.isInteger(version) || version < 0) {
        throw new Error('偏好版本标记无效');
      }
      if (version > 1) {
        throw new Error('偏好数据版本较新,请使用支持该版本的应用');
      }
      if (version === 0) {
        const rawSpeed = await this.store.get('speed', 1.0);
        const rawAutoNext = await this.store.get('autoNext', true);
        const speed = typeof rawSpeed === 'number' && validSpeed(rawSpeed)
          ? rawSpeed : 1.0;
        const autoNext = typeof rawAutoNext === 'boolean' ? rawAutoNext : true;
        await this.store.put('speed', speed);
        await this.store.put('autoNext', autoNext);
        await this.store.put('schemaVersion', 1);
      }
      await this.store.flush();
    });
  }

  private async readCurrent(): Promise<PlaybackSettings> {
    const rawSpeed = await this.store.get('speed', 1.0);
    const rawAutoNext = await this.store.get('autoNext', true);
    const speed = typeof rawSpeed === 'number' && validSpeed(rawSpeed) ? rawSpeed : 1.0;
    const autoNext = typeof rawAutoNext === 'boolean' ? rawAutoNext : true;
    return { speed, autoNext };
  }
  load(): Promise<PlaybackSettings> {
    return this.queue.enqueue<PlaybackSettings>(() => this.readCurrent());
  }

  save(value: PlaybackSettings): Promise<void> {
    if (!validSpeed(value.speed) || typeof value.autoNext !== 'boolean') {
      return Promise.reject(new Error('播放偏好不符合约定'));
    }
    const snapshot: PlaybackSettings = {
      speed: value.speed,
      autoNext: value.autoNext
    };
    return this.queue.enqueue<void>(async () => {
      await this.store.put('speed', snapshot.speed);
      await this.store.put('autoNext', snapshot.autoNext);
      await this.store.flush();
      this.publish(snapshot);
    });
  }
}

每次通知都复制两个标量字段,订阅者修改收到的对象不会改掉下一位订阅者的数据。发布前复制订阅条目列表,投递前再确认条目仍有效,允许某个回调释放其他订阅。释放函数按编号移除条目,多次调用也不会影响新的订阅。

回调异常单独隔离,不把某个页面的展示错误变成仓储保存失败。实际工程可以在隔离分支记录不含偏好原文的诊断信息。回调应保持同步、轻量;需要触发后续仓储操作时可以另行入队,但不能在通知链里阻塞等待一项必须等当前队列任务结束的工作。

三、页面获得通知,但不交出草稿所有权

如果收到快照就直接覆盖speed和autoNext,快捷入口的问题解决了,上一节保护用户编辑的工作却被撤销。页面继续使用speedDirty和autoNextDirty:未编辑字段接受通知,已编辑字段保留当前值。revision仍用于比较提交时草稿与保存完成时草稿,不被订阅编号替代。

下面替换entry/src/main/ets/pages/PreferencesPage.ets。页面路由登记与EntryAbility加载方式保持上一节约定。初始化以watch代替load,首个回调承担初始合并;watch完成之后才把仓储交给保存入口。

import { common } from '@kit.AbilityKit';
import { PodcastSettings, PlaybackSettings, validSpeed } from '../data/PodcastSettings';

@Entry
@Component
struct PreferencesPage {
  @State private speed: number = 1.0;
  @State private autoNext: boolean = true;
  @State private ready: boolean = false;
  @State private saving: boolean = false;
  @State private message: string = '正在读取偏好';
  private repository: PodcastSettings | undefined = undefined;
  private releaseSubscription: () => void = () => {};
  private alive: boolean = false;
  private epoch: number = 0;
  private revision: number = 0;
  private speedDirty: boolean = false;
  private autoNextDirty: boolean = false;

  aboutToAppear(): void { this.alive = true; this.initialize(); }
  aboutToDisappear(): void { this.alive = false; this.epoch++; this.releaseSubscription(); this.releaseSubscription = () => {}; }
  private async initialize(): Promise<void> {
    this.releaseSubscription();
    this.releaseSubscription = () => {};
    const token = ++this.epoch;
    this.ready = false;
    this.saving = false;
    this.repository = undefined;
    this.message = '正在读取偏好,仍可编辑';
    try {
      const context = getContext(this) as common.UIAbilityContext;
      const repository = await PodcastSettings.open(context);
      const release = await repository.watch((loaded: PlaybackSettings) => {
        if (!this.alive || token !== this.epoch) return;
        if (!this.speedDirty) this.speed = loaded.speed;
        if (!this.autoNextDirty) this.autoNext = loaded.autoNext;
      });
      if (!this.alive || token !== this.epoch) { release(); return; }
      this.releaseSubscription = release;
      this.repository = repository;
      this.ready = true;
      this.message = '读取完成,可保存当前草稿';
    } catch (_) {
      if (this.alive && token === this.epoch) this.message = '读取失败,草稿保留,可重试';
    }
  }
  private editSpeed(value: number): void {
    if (!validSpeed(value)) return;
    this.speed = value;
    this.speedDirty = true;
    this.revision++;
    this.message = '有未保存修改';
  }
  private editAutoNext(value: boolean): void {
    this.autoNext = value;
    this.autoNextDirty = true;
    this.revision++;
    this.message = '有未保存修改';
  }
  private async saveDraft(): Promise<void> {
    const repository = this.repository;
    if (!this.ready || this.saving || repository === undefined) return;
    const token = this.epoch;
    const sentRevision = this.revision;
    const snapshot: PlaybackSettings = { speed: this.speed, autoNext: this.autoNext };
    this.saving = true;
    this.message = '正在保存';
    try {
      await repository.save(snapshot);
      if (!this.alive || token !== this.epoch) return;
      if (sentRevision === this.revision) {
        this.speedDirty = false;
        this.autoNextDirty = false;
        this.message = '当前草稿已保存';
      } else {
        this.message = '上一份快照已保存,仍有新修改';
      }
    } catch (_) {
      if (this.alive && token === this.epoch) this.message = '保存失败,草稿保留';
    } finally {
      if (this.alive && token === this.epoch) this.saving = false;
    }
  }
  build() {
    Column({ space: 18 }) {
      Text('播客偏好').fontSize(28)
      Text('速度:' + this.speed.toFixed(2))
      Slider({ value: this.speed, min: 0.5, max: 2.0, step: 0.25 })
        .onChange((value: number) => { this.editSpeed(value); })
      Toggle({ type: ToggleType.Switch, isOn: this.autoNext })
        .onChange((value: boolean) => { this.editAutoNext(value); })
      Text('自动续播')
      Text(this.message)
      Button('保存偏好').enabled(this.ready && !this.saving)
        .onClick(() => { this.saveDraft(); })
      Button('重试读取').enabled(!this.ready)
        .onClick(() => { this.initialize(); })
    }.padding(24).width('100%')
  }
}

异步注册还有一个释放窗口:页面可能在watch返回释放函数以前就离开。回调内部先检查alive与epoch,防止改写旧页面;await返回后若已经过期,立即调用刚拿到的release。只在aboutToDisappear释放一个尚未赋值的字段,并不能回收未来才完成的注册。

重新初始化时先释放现有订阅,再推进epoch,避免重试不断叠加回调。释放函数保存在普通字段,展示状态才使用@State。页面退出只解除观察,不删除Preferences缓存,也不把整个仓储关闭,否则可能影响仍在使用它的其他入口。

订阅注册、通知和释放的状态边界

四、把演进后的关键路径逐个回放

先观察首个快照,再执行成功保存,应该收到后续提交。接着注入一次保存失败,确认没有成功通知;释放订阅后再次保存,旧回调不再计数。最后让注册结果迟到,在页面失效后拿到释放函数,立即释放,确认仓储不继续持有过期观察者。

本地模型检查覆盖上述顺序语义,也覆盖了释放函数重复调用。代码查看器加载本节源文件和检查输出,便于把watch实现与结果放在一起核对。它检查的是普通逻辑模型,目标设备仍需验证Preferences持久化、组件生命周期与实际界面更新。

本地代码查看器与订阅模型检查结果

保存期间再次编辑也是必要用例。自己的提交通知会在save完成之前发出,但dirty字段仍由用户草稿持有,因此不会被旧快照改回去。保存Promise完成后,只有sentRevision仍等于当前revision才清除dirty;否则提示仍有新修改。通知到达与提交确认分别有自己的判断依据。

五、现在可以同步到哪里

这里的订阅首值与后续通知还具有不同证据来源。首值来自注册时的当前读取,沿用仓储逐字段校验与默认值策略;后续通知来自本次成功save的输入副本。若此前一次失败已经部分改变缓存,首值也可能读到缓存中的值,所以它不是最近成功提交的历史回放。需要严格的已提交快照时,应另外维护并明确恢复失败后的状态。

使用订阅编号而不直接按函数引用移除,也让两次注册同一个函数仍然拥有各自的释放句柄。释放其中一次不会误删另一次,重试或组合页面中更容易解释所有权。页面应始终释放自己得到的句柄,不能通过清空整个订阅数组替其他消费者做决定。

批量通知期间新增订阅也有明确顺序。新增watch会进入队列,在当前保存任务结束以后读取首值;它不会被临时加入当前publish的遍历列表。这样新增观察者仍然通过自己的注册入口建立初值,不会先收到一个来源不明的中途事件,再反向补读旧状态。

释放只停止后续投递,不撤回已经执行中的同步回调。因此回调自身仍检查页面是否有效,不能把释放函数理解为任何时刻都能取消正在执行的代码。对于重计算或异步派生工作,还应增加自己的请求版本检查,避免订阅释放后派生结果继续写页面。

这个版本同步的是同一仓储实例中的成功提交,不提供多编辑会话的自动冲突合并。另一页面修改了用户正在编辑的字段,当前页仍保留草稿;之后保存可能覆盖对方值。需要避免覆盖时,应给仓储增加提交修订号与冲突策略,而不是简单把dirty清空来追随外部快照。

初始化失败、注册失败和普通保存失败也要分别处理。watch读取失败时没有新增订阅,页面可以重试;注册完成后离开则通过释放函数回收。已有持久化语义仍然来自Preferences,应用层通知并不会替它增加事务或跨进程一致性。

从load/save到watch,新增的不只是一个数组,而是一套首值、提交、失败和释放约定。最后一节处理恢复默认与顺序屏障时,将继续通过同一队列组织变更,并说明哪些操作可以通知、哪些失败应保留当前编辑状态,让连载最终收敛到可维护的仓储接口。

参考资料:Preferences订阅与持久化接口、Stage Context、组件生命周期。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐