.net - How to prevent Scan from running multiple times? -
for example
var subject = new subject<int>(); var test = subject.scan(0, (x, y) => { console.writeline("scan"); return x + 1; }); test.subscribe(x => console.writeline("subscribe1")); //test.subscribe(x => console.writeline("subscribe2")); observable.range(0, 1).subscribe(subject); console.writeline("done"); console.read();
the output is
scan subscribe1 done
but if uncomment second subscribe output is
scan subscribe1 scan subscribe2 done
why scan run 2 times , how can prevent it? output should
scan subscribe1 subscribe2 done
i use subject accumulate different observables. use scan method update model , have different places need subscribe model updates. maybe there better solution without using subject?
try using observable.publish
iconnectableobservable<t>
.
var subject = new subject<int>(); var test = subject .scan(0, (x, y) => { console.writeline("scan"); return x + 1; }) .publish(); test.subscribe(x => console.writeline("subscribe1")); test.subscribe(x => console.writeline("subscribe2")); test.connect(); observable.range(0, 1).subscribe(subject); console.writeline("done"); console.read();
output:
scan subscribe1 subscribe2 done
publish
turns cold scan
observable hot observable begins emitting values when connect
called.
Comments
Post a Comment