@@ -24,10 +24,14 @@ type NormalizeAutoStoreSyncerOptions = Required<Omit<AutoStoreSyncerOptions, 'fr
24
24
to : string [ ]
25
25
} >
26
26
27
+
28
+ export const SYNC_INIT_FLAG = - 1
29
+
27
30
export class AutoStoreSyncer {
28
- static seq = 0
31
+ static seq = 9
29
32
private _options : NormalizeAutoStoreSyncerOptions
30
33
syncing : boolean = false
34
+ peer ?: AutoStoreSyncer
31
35
private _watcher : Watcher | undefined
32
36
private _operateCache : StateRemoteOperate [ ] = [ ] // 本地操作缓存,
33
37
private seq : number = 0 // 实例标识
@@ -46,7 +50,7 @@ export class AutoStoreSyncer {
46
50
if ( typeof ( this . _options . to ) === 'string' ) this . _options . to = ( this . _options . to as string ) . split ( PATH_DELIMITER )
47
51
this . seq = ++ AutoStoreSyncer . seq
48
52
this . _options . autostart && this . start ( )
49
- if ( this . options . immediate ) this . push ( )
53
+ if ( this . options . immediate ) this . push ( true )
50
54
}
51
55
get id ( ) { return this . _options . id }
52
56
get options ( ) { return this . _options }
@@ -78,7 +82,9 @@ export class AutoStoreSyncer {
78
82
if ( isFunction ( this . _options . filter ) ) {
79
83
if ( this . _options . filter ( operate ) === false ) return
80
84
}
81
- if ( operate . flags === this . seq ) return
85
+ // 为什么要Math.abs?
86
+ // 在初始化进行第一次同步时传送seq时使用了负数,这样就可以让接收方区分是否是第一次同步
87
+ if ( Math . abs ( operate . flags || 0 ) === this . seq ) return
82
88
if ( this . options . direction === "backward" ) return
83
89
this . _sendToRemote ( operate )
84
90
} , {
@@ -165,7 +171,7 @@ export class AutoStoreSyncer {
165
171
166
172
const toPath = [ ...this . entry , ...operate . path . slice ( this . options . to . length ) ]
167
173
const updateOpts = {
168
- flags : this . seq
174
+ flags : operate . flags === SYNC_INIT_FLAG ? - this . seq : this . seq
169
175
}
170
176
if ( type === 'set' || type === 'update' ) {
171
177
this . store . update ( state => {
@@ -251,8 +257,11 @@ export class AutoStoreSyncer {
251
257
}
252
258
/**
253
259
* 将本地store推送到远程
260
+ *
261
+ * @param initial 是否是第一次同步
262
+ *
254
263
*/
255
- push ( ) {
264
+ push ( initial : boolean = false ) {
256
265
const localSnap = this . _getLocalSnap ( )
257
266
if ( typeof ( this . _options . pathMap . toRemote ) === 'function' ) {
258
267
forEachObject ( localSnap , ( { value, path } ) => {
@@ -264,6 +273,7 @@ export class AutoStoreSyncer {
264
273
path : [ ... this . options . to , ...toPath ] ,
265
274
value : toValue
266
275
} as StateRemoteOperate
276
+ if ( initial ) operate . flags = SYNC_INIT_FLAG
267
277
this . _sendOperate ( operate )
268
278
}
269
279
} )
@@ -273,7 +283,7 @@ export class AutoStoreSyncer {
273
283
type : '$push' ,
274
284
path : this . options . to ,
275
285
value : localSnap ,
276
- flags : 0
286
+ flags : initial ? SYNC_INIT_FLAG : 0
277
287
} as StateRemoteOperate )
278
288
}
279
289
}
0 commit comments