HarmonyOS 连载06:任务台断网续传与幂等提交账本的状态收敛【共创稿事节】
一次批量更新结束后,任务台最难处理的并不是显示“成功”,而是用户已经看到即时反馈,连接却在服务端确认与客户端收到结果之间中断。按钮重试看似简单:重新提交同一状态即可。但如果服务端已经处理了第一次请求,第二次就可能让版本号再次增加,其他页面据此产生冲突。前五篇逐步建立了稳定的 selectedId、基于原始任务集的筛选投影、异步读取代次、单条乐观覆盖,以及逐项结算的批量账本。现在需要给这条链补上最后一环:离开页面和重新进入后,尚未确认的写入意图依旧可追踪,而且不会被当作新操作重复执行。

“等待响应”与“操作失败”不能画等号
假设“完善需求评审”当前修订号为 3,用户把它标记为“已完成”,客户端带着预期版本 3 提交。请求到达服务端,任务更新为版本 4,响应在途中丢失。此时如果直接用版本 3 再试一次,服务端可能返回版本冲突;客户端既不知道第一次是否成功,也不应该把新一次点击解释为另一次任务状态变更。
因此,应将一次写入意图独立编码为 operationKey。网络重试沿用同一个键,只有用户主动在新版本上重新发起修改时才生成新的键。页面用 operationKey 识别业务写入;前文 operation 数字继续用于隔离 UI 层过期回包。二者解决的是不同层次的重复问题。
本篇将状态划分为 confirmed 和 outbox。前者只存已确认实体,后者存未最终结算的意图;屏幕显示的 displayRows 根据这两层合成。outbox 先持久化,再调用提交网关。只有收到具有确定结论的确认结果,才删除对应意图。连接暂时不可用或者返回信息不完整时,保留账本,等待下一次明确的恢复动作。
| 情形 | 本地账本 | 已确认任务 | 页面处理 |
|---|---|---|---|
| 连接不可用 | 保留原操作键 | 不改变 | 展示等待提交 |
| 服务端确认成功 | 移除对应条目 | 接纳新版本 | 展示已完成 |
| 服务端提示版本冲突 | 移除对应条目 | 刷新冲突实体 | 提醒重新核对 |
| 回包丢失 | 保留原操作键 | 暂不推进 | 下次沿同一键重放 |
把写入意图先存进 Preferences
Preferences 适合保存少量 KV 数据。本篇用单独的 task_outbox 文件保存一个小规模操作数组,不把整个任务列表塞进同一个键里。写入顺序必须固定为“先写本地账本、后调用网关”;否则页面退出时,用户已经点击的操作可能连记录都没有。这里的 flush() 与第二条连载中的草稿保存遵循同样的写入边界,但二者保存的是不同业务对象,不能复用一个 Preferences 文件。
以下类封装了本地操作账本,并完整给出序列化、读取校验和删除逻辑。remove() 在成功写入新数组之后才更新内存;读回时遇到结构不合法的值,会抛出异常供页面显示处理提示,而不是悄悄清空历史写入意图。
// TaskOutbox.ets
import { preferences } from '@kit.ArkData';
export enum TaskStatus {
Todo = '待处理', Doing = '进行中', Done = '已完成'
}
export interface TaskRecord {
id: string;
title: string;
status: TaskStatus;
version: number;
}
export interface QueuedChange {
operationKey: string;
id: string;
expectedVersion: number;
target: TaskStatus;
createdAt: number;
}
export interface CommitReply {
kind: 'accepted' | 'conflict';
value: TaskRecord;
}
export class TaskOutbox {
private prefs: preferences.Preferences | null = null;
private entries: QueuedChange[] = [];
async open(context: Context): Promise<QueuedChange[]> {
this.prefs = await preferences.getPreferences(context,
{ name: 'task_outbox' });
const raw: string = String(await this.prefs.get('pending_changes', '[]'));
const parsed: QueuedChange[] = JSON.parse(raw) as QueuedChange[];
if (!Array.isArray(parsed) || parsed.length > 60 ||
parsed.some((item: QueuedChange): boolean =>
typeof item.operationKey !== 'string' ||
item.operationKey.length < 4 ||
typeof item.id !== 'string' ||
!Number.isSafeInteger(item.expectedVersion) ||
item.expectedVersion < 0 ||
!Number.isSafeInteger(item.createdAt) ||
(item.target !== TaskStatus.Todo &&
item.target !== TaskStatus.Doing &&
item.target !== TaskStatus.Done))) {
throw new Error('待提交账本结构异常');
}
this.entries = parsed;
return [...this.entries];
}
list(): QueuedChange[] {
return [...this.entries];
}
private async persist(next: QueuedChange[]): Promise<void> {
if (!this.prefs) { throw new Error('账本尚未打开'); }
await this.prefs.put('pending_changes', JSON.stringify(next));
await this.prefs.flush();
this.entries = next;
}
async append(item: QueuedChange): Promise<void> {
if (this.entries.some((row: QueuedChange): boolean => row.id === item.id)) {
throw new Error('此任务仍有待确认操作');
}
await this.persist([...this.entries, item]);
}
async remove(key: string): Promise<void> {
await this.persist(this.entries.filter((row: QueuedChange): boolean =>
row.operationKey !== key));
}
}
Object.values() 在项目启用较严格的 ArkTS 静态检查时可改为显式枚举比较,避免以松散对象承载业务类型。更重要的是,persist() 同时更新 Preferences 缓存和页面内存;实际工程中若需要应对 put() 已生效、flush() 失败的情形,应禁止继续发送该次提交,并提供重新读取和修复路径,不能无条件推进网络写入。
提交网关必须尊重同一个操作键
下面的网关在当前页面内保留确认账本,用于把“重复传输一次请求”和“重新执行一次业务修改”区分开。接入服务时,operationKey 必须传给服务端,并由服务端使用持久化的幂等记录执行去重;单靠页面内的 Map,无法覆盖进程退出后再次到达的请求。任务版本比较也应该放在服务端原子事务中。
// TaskGateway.ets
import { TaskRecord, TaskStatus, QueuedChange, CommitReply } from './TaskOutbox';
export class TaskGateway {
private rows: TaskRecord[] = [
{ id: 'review', title: '完善需求评审', status: TaskStatus.Todo, version: 3 },
{ id: 'api', title: '联调接口', status: TaskStatus.Doing, version: 2 },
{ id: 'release', title: '版本发布准备', status: TaskStatus.Todo, version: 4 }
];
private receipts: Map<string, CommitReply> = new Map<string, CommitReply>();
list(): TaskRecord[] { return this.rows.map((item: TaskRecord): TaskRecord => ({ ...item })); }
async commit(change: QueuedChange): Promise<CommitReply> {
const old: CommitReply | undefined = this.receipts.get(change.operationKey);
if (old) { return old; }
const current: TaskRecord | undefined = this.rows.find(
(item: TaskRecord): boolean => item.id === change.id);
if (!current) { throw new Error('任务已移除,请先刷新任务列表'); }
let reply: CommitReply;
if (current.version !== change.expectedVersion) {
reply = { kind: 'conflict', value: { ...current } };
} else {
const next: TaskRecord = {
...current, status: change.target, version: current.version + 1
};
this.rows = this.rows.map((row: TaskRecord): TaskRecord =>
row.id === next.id ? next : row);
reply = { kind: 'accepted', value: next };
}
this.receipts.set(change.operationKey, reply);
return reply;
}
}
页面层再负责两件事:持久化新增写入意图,以及将确认结果合并回原始任务集。它保留 selectedId,不让队列变化重置右侧详情。这里提供一份独立的 ArkUI 页面,列出本次写入的核心交互和恢复入口。后续接上第一篇的宽度监听器,双栏详情继续按身份查找原始合成集合即可。
// TaskRecoveryPage.ets
import { TaskOutbox, TaskRecord, TaskStatus, QueuedChange } from './TaskOutbox';
import { TaskGateway } from './TaskGateway';
@Entry
@Component
struct TaskRecoveryPage {
@State private confirmed: TaskRecord[] = [];
@State private queue: QueuedChange[] = [];
@State private selectedId: string = 'api';
@State private notice: string = '读取待确认操作';
@State private busy: boolean = false;
private outbox: TaskOutbox = new TaskOutbox();
private gateway: TaskGateway = new TaskGateway();
private serial: number = 0;
aboutToAppear(): void { this.restore(); }
private async restore(): Promise<void> {
try {
this.confirmed = this.gateway.list();
this.queue = await this.outbox.open(getContext(this));
this.notice = '已恢复 ' + this.queue.length + ' 条待确认操作';
} catch (error) {
this.notice = '账本读取失败,请检查存储后重试';
}
}
private displayRows(): TaskRecord[] {
return this.confirmed.map((row: TaskRecord): TaskRecord => {
const intent: QueuedChange | undefined = this.queue.find(
(item: QueuedChange): boolean => item.id === row.id);
return intent ? { ...row, status: intent.target } : row;
});
}
private async markDone(row: TaskRecord): Promise<void> {
if (this.busy) { return; }
this.busy = true;
try {
const intent: QueuedChange = {
operationKey: row.id + '-' + Date.now() + '-' + (++this.serial),
id: row.id, expectedVersion: row.version,
target: TaskStatus.Done, createdAt: Date.now()
};
await this.outbox.append(intent);
this.queue = this.outbox.list();
this.notice = '操作已进入待提交账本';
} catch (error) {
this.notice = '操作记录失败,请重试';
} finally {
this.busy = false;
}
}
private async replay(): Promise<void> {
if (this.busy) { return; }
this.busy = true;
try {
const copies: QueuedChange[] = this.outbox.list();
for (const item of copies) {
try {
const reply = await this.gateway.commit(item);
this.confirmed = this.confirmed.map((row: TaskRecord): TaskRecord =>
row.id === reply.value.id && row.version <= reply.value.version ?
reply.value : row);
await this.outbox.remove(item.operationKey);
this.queue = this.outbox.list();
this.notice = reply.kind === 'accepted' ? '已确认:' + item.id :
'版本冲突:' + item.id + ',请核对后重新提交';
} catch (error) {
this.notice = '部分操作仍在等待确认';
}
}
} finally { this.busy = false; }
}
build() {
Column({ space: 12 }) {
Text('任务台 · 写入恢复').fontSize(24).fontWeight(FontWeight.Bold)
Text('待确认 ' + this.queue.length + ' 条').fontColor('#0369A1')
List({ space: 10 }) {
ForEach(this.displayRows(), (row: TaskRecord) => {
ListItem() {
Column({ space: 8 }) {
Row() {
Text(row.title).fontSize(17).layoutWeight(1)
Text(row.status).fontColor('#0F766E')
}
Row() {
Button('查看').onClick(() => { this.selectedId = row.id; })
Button('标记完成').onClick(() => { this.markDone(row); })
}
}.padding(14).backgroundColor('#F0F9FF').borderRadius(12)
}
}, (row: TaskRecord): string => row.id)
}.layoutWeight(1)
Text('当前详情:' + this.selectedId).fontColor('#334155')
Text(this.notice).fontSize(12).fontColor('#B45309')
Button('恢复连接后继续提交').width('100%')
.onClick(() => { this.replay(); })
}.padding(16).width('100%').height('100%')
}
}

有三条顺序约束,不能靠界面提示补救
第一,本地确认记录更新与出站账本删除的先后必须有明确的恢复策略。上例先收取网关确认,更新内存,再删除本地条目。如果删除落盘失败,原始操作键仍在下次读取时出现,可以再次向服务端查询该键对应的结算结果;拥有持久化去重能力的服务端必须返回之前的确认而非再次执行。这个过程使界面无需猜测“是不是已经成功”。
第二,连接恢复不是自动清空错误。版本冲突是确定性失败,应刷新实体后由用户重新选择新的修改意图;网络中断则属于未确认状态,保留旧意图。把两类异常都放进“失败列表”再一键重试,容易在多端编辑时覆盖别人的结果。
第三,队列恢复与查询刷新不能使用两套彼此矛盾的投影。原始任务实体来自已确认仓库,待提交状态来自 outbox。筛选页和详情页分别读取投影后的全量集合,再决定局部可见性。用户正在查看 api 任务时,另一个 review 任务的回包不应清空 selectedId。这一点是前五篇状态设计在弱连接条件下仍能成立的关键。
先列事件,再判断页面是否正确
可以按下面的事件顺序核查实现:提交任务,确认 Preferences 已存下 operationKey;暂时停止网关处理,重新进入页面后操作数量不变;恢复网关,确认同一键只形成一次业务变化;对已有新版本的任务提交旧 expectedVersion,只更新该任务的冲突状态;在待处理筛选中等待提交结束,列表重新计算,但详情身份保持不变。针对真实服务,还应设计响应确认后进程退出、恢复后重复发送、两个设备同时写入等测试条件。
网络事件适配层负责把连接状态转换为重试触发,不应该直接改变业务版本。大批量操作也不适合全部长期积压于 Preferences:这里通过数量上限约束账本规模,超出规模可转向面向业务事务的数据存储,并加入退避、用户取消、过期操作清理与后台时机控制。

ArkUI 的数据驱动更新可参考状态管理指南,本地账本的 getPreferences()、put() 与 flush() 行为可参考Preferences API。回顾这组六篇连载,宽度变化、列表筛选、异步搜索、乐观更新、批量归并与断网续传虽然属于不同交互问题,最终都落实在同一条原则上:稳定身份来自业务键,最终状态来自确认记录,暂时变化必须带着可追溯的操作边界。
更多推荐

所有评论(0)