HarmonyOS 5.0.0 或以上:封装分布式状态同步服务(统一数据仓库 + 双向绑定)


📌 场景说明

在分布式项目中,常需要多设备共享同一状态(如用户信息、协作数据、界面状态等)。如果每个字段都独立同步,会造成:

  • 状态不集中、难以管理

  • 同步行为散落各处,测试难

  • 页面绑定麻烦、监听复杂

本篇目标:

✅ 封装一个全局状态服务 DistributedStateStore
支持设置和获取共享状态
支持响应式双向绑定(如绑定表单输入框)


🧱 文件结构

/entry/src/main/ets
  ├── services/
  │     └── DistributedStateStore.ets     // 分布式状态仓库封装
  └── pages/
        └── SyncFormDemo.ets              // 双向绑定使用示例

🧩 services/DistributedStateStore.ets

import distributedData from '@ohos.distributedData'

type StateListener = (val: string) => void

export class DistributedStateStore {
  private static instance: DistributedStateStore
  private kvStore: distributedData.SingleKvStore | undefined
  private listenerMap: Map<string, StateListener[]> = new Map()

  static async getInstance(context: Context): Promise<DistributedStateStore> {
    if (!this.instance) {
      this.instance = new DistributedStateStore()
      await this.instance.init(context)
    }
    return this.instance
  }

  private async init(context: Context) {
    const manager = distributedData.createKVManager({
      context,
      bundleName: 'com.example.harmony',
      userInfo: { userId: '0', userType: distributedData.UserType.SAME_USER_ID }
    })

    this.kvStore = await manager.getSingleKvStore({
      storeId: 'shared_state',
      options: {
        createIfMissing: true,
        encrypt: false,
        backup: false,
        autoSync: true,
        kvStoreType: distributedData.KvStoreType.SINGLE_VERSION
      }
    })

    this.kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (changes) => {
      for (const entry of changes.insertEntries) {
        const cbs = this.listenerMap.get(entry.key)
        if (cbs) {
          for (const cb of cbs) cb(entry.value.value as string)
        }
      }
    })
  }

  async set(key: string, value: string) {
    await this.kvStore?.put(key, value)
  }

  async get(key: string): Promise<string> {
    try {
      return await this.kvStore?.get(key) || ''
    } catch {
      return ''
    }
  }

  on(key: string, callback: StateListener) {
    if (!this.listenerMap.has(key)) this.listenerMap.set(key, [])
    this.listenerMap.get(key)?.push(callback)
  }

  off(key: string, callback: StateListener) {
    const list = this.listenerMap.get(key) || []
    this.listenerMap.set(key, list.filter(cb => cb !== callback))
  }
}

🧩 pages/SyncFormDemo.ets(页面使用示例)

import { DistributedStateStore } from '../services/DistributedStateStore'

@Entry
@Component
struct SyncFormDemo {
  @State nickname: string = ''
  @State syncLabel: string = '--'
  private store?: DistributedStateStore
  private key = 'user_nickname'

  async aboutToAppear() {
    const context = getContext(this)
    this.store = await DistributedStateStore.getInstance(context)
    this.nickname = await this.store.get(this.key)
    this.store.on(this.key, (val) => {
      this.nickname = val
      this.syncLabel = `🛰 来自远程更新:${val}`
    })
  }

  private async updateNickname(val: string) {
    this.nickname = val
    await this.store?.set(this.key, val)
    this.syncLabel = `✅ 本地修改:${val}`
  }

  build() {
    Column() {
      Text("👥 分布式昵称同步表单").fontSize(22).margin(20)

      TextInput({
        text: this.nickname,
        placeholder: '请输入昵称',
        onChange: val => this.updateNickname(val)
      })
      .width('100%')
      .marginBottom(10)

      Text(this.syncLabel).fontSize(14).fontColor('#888')
      Text("💡 多端共享状态,可跨端双向编辑").fontSize(12).fontColor('#999').marginTop(30)
    }
    .padding(20)
    .height('100%')
  }
}

✅ 效果说明

  • 每台设备修改昵称后,所有设备的输入框内容都会实时同步更新

  • 通过封装的 DistributedStateStore 实现全局状态共享

  • 同时具备存储、监听、响应式更新能力


🔧 拓展建议

  • 状态持久化类型支持:number, JSON, boolean

  • 扩展 setLocal() 实现仅本地设置(无广播)

  • 支持监听键前缀(如所有 form_* 字段)实现动态表单协同

  • 封装为小型跨端状态管理框架(如 mini Pinia for 分布式)

Logo

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

更多推荐