优化ObservableImpl
This commit is contained in:
@@ -10,68 +10,69 @@ import type {
|
|||||||
* 创建一个可观察对象,用于管理状态和事件。
|
* 创建一个可观察对象,用于管理状态和事件。
|
||||||
* @template T - 需要处理的状态类型
|
* @template T - 需要处理的状态类型
|
||||||
* @example
|
* @example
|
||||||
|
* interface Todo {
|
||||||
|
* id: number
|
||||||
|
* text: string
|
||||||
|
* done: boolean
|
||||||
|
* }
|
||||||
|
*
|
||||||
* interface AppState {
|
* interface AppState {
|
||||||
* count: number
|
* count: number
|
||||||
|
* todos: Todo[]
|
||||||
* user: {
|
* user: {
|
||||||
* name: string
|
* name: string
|
||||||
* age: number
|
* age: number
|
||||||
* }
|
* }
|
||||||
* items: number[]
|
* inc(): void
|
||||||
* }
|
* }
|
||||||
*
|
*
|
||||||
* // 创建 ObservableImpl
|
|
||||||
* const obs = new ObservableImpl<AppState>({
|
* const obs = new ObservableImpl<AppState>({
|
||||||
* count: 0,
|
* count: 0,
|
||||||
* user: { name: 'Alice', age: 20 },
|
* todos: [],
|
||||||
* items: []
|
* user: { name: "Alice", age: 20 },
|
||||||
|
* inc() {
|
||||||
|
* this.count++ // ✅ this 指向 obs.state
|
||||||
|
* },
|
||||||
* })
|
* })
|
||||||
*
|
*
|
||||||
* // 1️⃣ 全量订阅
|
* // ================== 使用示例 ==================
|
||||||
* const unsubscribeAll = obs.subscribe(state => {
|
|
||||||
* console.log('全量订阅', state)
|
|
||||||
* }, { immediate: true })
|
|
||||||
*
|
*
|
||||||
* // 2️⃣ 单字段订阅
|
* // 1. 订阅整个 state
|
||||||
* const unsubscribeCount = obs.subscribeKey('count', ({ count }) => {
|
* obs.subscribe(state => {
|
||||||
* console.log('count 字段变化:', count)
|
* console.log("[全量订阅] state 更新:", state)
|
||||||
* })
|
* })
|
||||||
*
|
*
|
||||||
* // 3️⃣ 多字段订阅
|
* // 2. 订阅单个字段
|
||||||
* const unsubscribeUser = obs.subscribeKey(['user', 'count'], ({ user, count }) => {
|
* obs.subscribeKey("count", ({ count }) => {
|
||||||
* console.log('user 或 count 变化:', { user, count })
|
* console.log("[字段订阅] count 更新:", count)
|
||||||
* })
|
* })
|
||||||
*
|
*
|
||||||
* // 4️⃣ 修改属性
|
* // 3. 订阅多个字段
|
||||||
* obs.state.count = 1 // ✅ 会触发 count 和全量订阅
|
* obs.subscribeKey(["name", "age"] as (keyof AppState["user"])[], (user) => {
|
||||||
* obs.state.user.age = 21 // ✅ 深层对象修改触发 user 订阅
|
* console.log("[多字段订阅] user 更新:", user)
|
||||||
* obs.state.user.name = 'Bob'
|
|
||||||
* // 语法糖:解构赋值直接赋值触发通知
|
|
||||||
* const { count, user, items } = obs.toRefsProxy()
|
|
||||||
* count = 1 // 触发 Proxy set
|
|
||||||
* user.age = 18 // 深层对象 Proxy 支持
|
|
||||||
* items.push(42) // 数组方法拦截触发通知
|
|
||||||
*
|
|
||||||
* // 5️⃣ 数组方法触发
|
|
||||||
* obs.state.items.push(10) // ✅ push 会触发 items 的字段订阅
|
|
||||||
* obs.state.items.splice(0, 1)
|
|
||||||
*
|
|
||||||
* // 6️⃣ 批量修改(同一事件循环只触发一次通知)
|
|
||||||
* obs.patch({
|
|
||||||
* count: 2,
|
|
||||||
* user: { name: 'Charlie', age: 30 }
|
|
||||||
* })
|
* })
|
||||||
*
|
*
|
||||||
* // 7️⃣ 解构赋值访问对象属性仍然触发订阅
|
* // 4. 批量更新
|
||||||
* const { state } = obs
|
* obs.patch({ count: 10, user: { name: "Bob", age: 30 } })
|
||||||
* state.user.age = 31 // ✅ 会触发 user 订阅
|
|
||||||
*
|
*
|
||||||
* // 8️⃣ 取消订阅
|
* // 5. 方法里操作 state
|
||||||
* unsubscribeAll()
|
* obs.state.inc() // this.count++ → 相当于 obs.state.count++
|
||||||
* unsubscribeCount()
|
|
||||||
* unsubscribeUser()
|
|
||||||
*
|
*
|
||||||
* // 9️⃣ 销毁 ObservableImpl
|
* // 6. 数组操作
|
||||||
* obs.dispose()
|
* obs.subscribeKey("todos", ({ todos }) => {
|
||||||
|
* console.log("[数组订阅] todos 更新:", todos.map(t => t.text))
|
||||||
|
* })
|
||||||
|
*
|
||||||
|
* obs.state.todos.push({ id: 1, text: "Buy milk", done: false })
|
||||||
|
* obs.state.todos.push({ id: 2, text: "Read book", done: false })
|
||||||
|
* obs.state.todos[0].done = true
|
||||||
|
*
|
||||||
|
* // 7. 嵌套对象
|
||||||
|
* obs.subscribeKey("user", ({ user }) => {
|
||||||
|
* console.log("[嵌套订阅] user 更新:", user)
|
||||||
|
* })
|
||||||
|
*
|
||||||
|
* obs.state.user.age++
|
||||||
*/
|
*/
|
||||||
export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObservable<T> {
|
export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObservable<T> {
|
||||||
/** Observable 状态对象,深层 Proxy */
|
/** Observable 状态对象,深层 Proxy */
|
||||||
@@ -81,7 +82,7 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
|
|||||||
private listeners: Set<TObservableListener<T>> = new Set()
|
private listeners: Set<TObservableListener<T>> = new Set()
|
||||||
|
|
||||||
/** 字段订阅函数集合 */
|
/** 字段订阅函数集合 */
|
||||||
private keyListeners: Map<keyof T, Set<Function>> = new Map()
|
private keyListeners: Map<keyof T, Set<TObservableKeyListener<T, keyof T>>> = new Map()
|
||||||
|
|
||||||
/** 待通知的字段集合 */
|
/** 待通知的字段集合 */
|
||||||
private pendingKeys: Set<keyof T> = new Set()
|
private pendingKeys: Set<keyof T> = new Set()
|
||||||
@@ -92,56 +93,73 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
|
|||||||
/** 是否已销毁 */
|
/** 是否已销毁 */
|
||||||
private disposed = false
|
private disposed = false
|
||||||
|
|
||||||
|
/** 缓存 Proxy,避免重复包装 */
|
||||||
|
private proxyCache: WeakMap<object, TObservableState<unknown>> = new WeakMap()
|
||||||
|
|
||||||
constructor(initialState: TNonFunctionProperties<T>) {
|
constructor(initialState: TNonFunctionProperties<T>) {
|
||||||
// 创建深层响应式 Proxy
|
// 创建深层响应式 Proxy
|
||||||
this.state = this.makeReactive(initialState) as TObservableState<T>
|
this.state = this.makeReactive(initialState) as TObservableState<T>
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 创建深层 Proxy,拦截 get/set */
|
/** 创建深层 Proxy,拦截 get/set/delete,并自动缓存 */
|
||||||
private makeReactive(obj: TNonFunctionProperties<T>): TObservableState<T> {
|
private makeReactive<O extends object>(obj: O): TObservableState<O> {
|
||||||
const handler: ProxyHandler<any> = {
|
// 非对象直接返回(包括 null 已被排除)
|
||||||
get: (target, prop: string | symbol, receiver) => {
|
if (typeof obj !== "object" || obj === null) {
|
||||||
const key = prop as keyof T
|
return obj as unknown as TObservableState<O>
|
||||||
const value = Reflect.get(target, key, receiver)
|
}
|
||||||
if (Array.isArray(value)) return this.wrapArray(value, key)
|
|
||||||
if (typeof value === 'object' && value !== null) return this.makeReactive(value)
|
// 如果已有 Proxy 缓存则直接返回
|
||||||
|
const cached = this.proxyCache.get(obj as object)
|
||||||
|
if (cached !== undefined) {
|
||||||
|
return cached as TObservableState<O>
|
||||||
|
}
|
||||||
|
|
||||||
|
const handler: ProxyHandler<O> = {
|
||||||
|
get: (target, prop, receiver) => {
|
||||||
|
const value = Reflect.get(target, prop, receiver) as unknown
|
||||||
|
// 不包装函数
|
||||||
|
if (typeof value === "function") {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
// 对对象/数组继续进行响应式包装(递归)
|
||||||
|
if (typeof value === "object" && value !== null) {
|
||||||
|
return this.makeReactive(value as object)
|
||||||
|
}
|
||||||
return value
|
return value
|
||||||
},
|
},
|
||||||
set: (target, prop: string | symbol, value, receiver) => {
|
|
||||||
const key = prop as keyof T
|
set: (target, prop, value, receiver) => {
|
||||||
const oldValue = target[key]
|
// 读取旧值(使用 Record 以便类型安全访问属性)
|
||||||
if (oldValue !== value) {
|
const oldValue = (target as Record<PropertyKey, unknown>)[prop as PropertyKey] as unknown
|
||||||
target[key] = value
|
const result = Reflect.set(target, prop, value as unknown, receiver)
|
||||||
this.pendingKeys.add(key)
|
// 仅在值改变时触发通知(基于引用/原始值比较)
|
||||||
|
if (!this.disposed && oldValue !== (value as unknown)) {
|
||||||
|
this.pendingKeys.add(prop as keyof T)
|
||||||
this.scheduleNotify()
|
this.scheduleNotify()
|
||||||
}
|
}
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return new Proxy(obj, handler) as TObservableState<T>
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 包装数组方法,使 push/pop 等触发通知 */
|
|
||||||
private wrapArray(arr: any[], parentKey: keyof T): any {
|
|
||||||
const self = this
|
|
||||||
const arrayMethods = ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'] as const
|
|
||||||
arrayMethods.forEach(method => {
|
|
||||||
const original = arr[method]
|
|
||||||
Object.defineProperty(arr, method, {
|
|
||||||
value: function (...args: any[]) {
|
|
||||||
const result = original.apply(this, args)
|
|
||||||
self.pendingKeys.add(parentKey)
|
|
||||||
self.scheduleNotify()
|
|
||||||
return result
|
return result
|
||||||
},
|
},
|
||||||
writable: true,
|
|
||||||
configurable: true,
|
deleteProperty: (target, prop) => {
|
||||||
})
|
if (prop in target) {
|
||||||
})
|
// 使用 Reflect.deleteProperty 以保持一致性
|
||||||
return arr
|
const deleted = Reflect.deleteProperty(target, prop)
|
||||||
|
if (deleted && !this.disposed) {
|
||||||
|
this.pendingKeys.add(prop as keyof T)
|
||||||
|
this.scheduleNotify()
|
||||||
|
}
|
||||||
|
return deleted
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 安排下一次通知 */
|
const proxy = new Proxy(obj, handler) as TObservableState<O>
|
||||||
|
this.proxyCache.set(obj as object, proxy as TObservableState<unknown>)
|
||||||
|
return proxy
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 安排下一次通知(微任务合并) */
|
||||||
private scheduleNotify(): void {
|
private scheduleNotify(): void {
|
||||||
if (!this.notifyScheduled && !this.disposed) {
|
if (!this.notifyScheduled && !this.disposed) {
|
||||||
this.notifyScheduled = true
|
this.notifyScheduled = true
|
||||||
@@ -149,40 +167,70 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 执行通知 */
|
/** 执行通知(聚合字段订阅并保证错误隔离) */
|
||||||
private flushNotify(): void {
|
private flushNotify(): void {
|
||||||
if (this.disposed) return
|
if (this.disposed) return
|
||||||
|
|
||||||
const keys = Array.from(this.pendingKeys)
|
const keys = Array.from(this.pendingKeys)
|
||||||
this.pendingKeys.clear()
|
this.pendingKeys.clear()
|
||||||
this.notifyScheduled = false
|
this.notifyScheduled = false
|
||||||
|
|
||||||
// 全量订阅
|
// 全量订阅 —— 每个订阅单独 try/catch,避免一个错误阻塞其它订阅
|
||||||
for (const fn of this.listeners) {
|
for (const fn of Array.from(this.listeners)) {
|
||||||
fn(this.state)
|
try {
|
||||||
|
fn(this.state as unknown as T)
|
||||||
|
} catch (err) {
|
||||||
|
// 可以根据需要把错误上报或自定义处理
|
||||||
|
// 这里简单打印以便调试
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error("Observable listener error:", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 字段订阅
|
// 字段订阅:把同一个回调的多个 key 聚合到一次调用里
|
||||||
const fnMap = new Map<Function, (keyof T)[]>()
|
const fnMap: Map<TObservableKeyListener<T, keyof T>, (keyof T)[]> = new Map()
|
||||||
for (const key of keys) {
|
for (const key of keys) {
|
||||||
const set = this.keyListeners.get(key)
|
const set = this.keyListeners.get(key)
|
||||||
if (!set) continue
|
if (!set) continue
|
||||||
for (const fn of set) {
|
for (const fn of Array.from(set)) {
|
||||||
if (!fnMap.has(fn)) fnMap.set(fn, [])
|
const existing = fnMap.get(fn)
|
||||||
fnMap.get(fn)!.push(key)
|
if (existing === undefined) {
|
||||||
|
fnMap.set(fn, [key])
|
||||||
|
} else {
|
||||||
|
existing.push(key)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 调用每个字段订阅回调
|
||||||
fnMap.forEach((subKeys, fn) => {
|
fnMap.forEach((subKeys, fn) => {
|
||||||
const result = {} as Pick<T, typeof subKeys[number]>
|
try {
|
||||||
subKeys.forEach(k => (result[k] = this.state[k]))
|
// 构造 Pick<T, K> 风格的结果对象:结果类型为 Pick<T, (typeof subKeys)[number]>
|
||||||
fn(result)
|
const result = {} as Pick<T, (typeof subKeys)[number]>
|
||||||
|
subKeys.forEach(k => {
|
||||||
|
// 这里断言原因:state 的索引访问返回 unknown,但我们把它赋回到受限的 Pick 上
|
||||||
|
result[k] = (this.state as Record<keyof T, unknown>)[k] as T[(typeof k) & keyof T]
|
||||||
|
})
|
||||||
|
// 调用时类型上兼容 TObservableKeyListener<T, K>,因为我们传的是对应 key 的 Pick
|
||||||
|
fn(result as unknown as any) // 最后一处转换仅为满足 TypeScript 调用签名(不引入 any 到实现变量)
|
||||||
|
} catch (err) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error("Observable keyListener error:", err)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 订阅整个状态变化 */
|
/** 订阅整个状态变化 */
|
||||||
public subscribe(fn: TObservableListener<T>, options: { immediate?: boolean } = {}): () => void {
|
public subscribe(fn: TObservableListener<T>, options: { immediate?: boolean } = {}): () => void {
|
||||||
this.listeners.add(fn)
|
this.listeners.add(fn)
|
||||||
if (options.immediate) fn(this.state)
|
if (options.immediate) {
|
||||||
|
try {
|
||||||
|
fn(this.state as unknown as T)
|
||||||
|
} catch (err) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error("Observable subscribe immediate error:", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
return () => {
|
return () => {
|
||||||
this.listeners.delete(fn)
|
this.listeners.delete(fn)
|
||||||
}
|
}
|
||||||
@@ -197,32 +245,48 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
|
|||||||
const keyArray = Array.isArray(keys) ? keys : [keys]
|
const keyArray = Array.isArray(keys) ? keys : [keys]
|
||||||
for (const key of keyArray) {
|
for (const key of keyArray) {
|
||||||
if (!this.keyListeners.has(key)) this.keyListeners.set(key, new Set())
|
if (!this.keyListeners.has(key)) this.keyListeners.set(key, new Set())
|
||||||
this.keyListeners.get(key)!.add(fn)
|
// 存储为 Set<TObservableKeyListener<T, keyof T>>
|
||||||
|
this.keyListeners.get(key)!.add(fn as TObservableKeyListener<T, keyof T>)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.immediate) {
|
if (options.immediate) {
|
||||||
const result = {} as Pick<T, K>
|
const result = {} as Pick<T, K>
|
||||||
keyArray.forEach(k => (result[k] = this.state[k]))
|
keyArray.forEach(k => {
|
||||||
|
result[k] = (this.state as Record<keyof T, unknown>)[k] as T[K]
|
||||||
|
})
|
||||||
|
try {
|
||||||
fn(result)
|
fn(result)
|
||||||
|
} catch (err) {
|
||||||
|
// eslint-disable-next-line no-console
|
||||||
|
console.error("Observable subscribeKey immediate error:", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
for (const key of keyArray) {
|
for (const key of keyArray) {
|
||||||
this.keyListeners.get(key)?.delete(fn)
|
this.keyListeners.get(key)?.delete(fn as TObservableKeyListener<T, keyof T>)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 批量更新状态 */
|
/** 批量更新状态(避免重复 schedule) */
|
||||||
public patch(values: Partial<T>): void {
|
public patch(values: Partial<T>): void {
|
||||||
|
let changed = false
|
||||||
|
// 用 for..in 保持和对象字面量兼容(跳过原型链)
|
||||||
for (const key in values) {
|
for (const key in values) {
|
||||||
if (Object.prototype.hasOwnProperty.call(values, key)) {
|
if (Object.prototype.hasOwnProperty.call(values, key)) {
|
||||||
const typedKey = key as keyof T
|
const typedKey = key as keyof T
|
||||||
this.state[typedKey] = values[typedKey]!
|
const oldValue = (this.state as Record<keyof T, unknown>)[typedKey]
|
||||||
this.pendingKeys.add(typedKey)
|
const newValue = values[typedKey] as unknown
|
||||||
|
if (oldValue !== newValue) {
|
||||||
|
// 直接写入 state,会被 Proxy 的 set 捕获并安排通知
|
||||||
|
;(this.state as Record<keyof T, unknown>)[typedKey] = newValue
|
||||||
|
changed = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.scheduleNotify()
|
}
|
||||||
|
// 如果至少有一处变化,安排一次通知(如果写入已由 set 调度过也不会重复安排)
|
||||||
|
if (changed) this.scheduleNotify()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 销毁 Observable 实例 */
|
/** 销毁 Observable 实例 */
|
||||||
@@ -231,27 +295,29 @@ export class ObservableImpl<T extends TNonFunctionProperties<T>> implements IObs
|
|||||||
this.listeners.clear()
|
this.listeners.clear()
|
||||||
this.keyListeners.clear()
|
this.keyListeners.clear()
|
||||||
this.pendingKeys.clear()
|
this.pendingKeys.clear()
|
||||||
|
this.proxyCache = new WeakMap()
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 语法糖:返回一个可解构赋值的 Proxy */
|
/** 语法糖:返回一个可解构赋值的 Proxy */
|
||||||
public toRefsProxy(): { [K in keyof T]: T[K] } {
|
public toRefsProxy(): { [K in keyof T]: T[K] } {
|
||||||
const self = this
|
const self = this
|
||||||
return new Proxy({} as T, {
|
return new Proxy({} as { [K in keyof T]: T[K] }, {
|
||||||
get(_, prop: string | symbol) {
|
get(_, prop: string | symbol) {
|
||||||
const key = prop as keyof T
|
const key = prop as keyof T
|
||||||
return self.state[key]
|
return (self.state as Record<keyof T, unknown>)[key] as T[typeof key]
|
||||||
},
|
},
|
||||||
set(_, prop: string | symbol, value) {
|
set(_, prop: string | symbol, value) {
|
||||||
const key = prop as keyof T
|
const key = prop as keyof T
|
||||||
self.state[key] = value
|
;(self.state as Record<keyof T, unknown>)[key] = value as unknown
|
||||||
return true
|
return true
|
||||||
},
|
},
|
||||||
ownKeys() {
|
ownKeys() {
|
||||||
return Reflect.ownKeys(self.state)
|
return Reflect.ownKeys(self.state)
|
||||||
},
|
},
|
||||||
getOwnPropertyDescriptor(_, prop: string | symbol) {
|
getOwnPropertyDescriptor(_, _prop: string | symbol) {
|
||||||
return { enumerable: true, configurable: true }
|
return { enumerable: true, configurable: true }
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user