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 you uncomment second Subscribe the output is
scan
subscribe1
scan
subscribe2
done
Why does the Scan run two times and how can I prevent it? So output should be
scan
subscribe1
subscribe2
done
I use Subject to accumulate different Observables. Then I use Scan method to update Model and then I have different places where I need to subscribe to Model updates. Maybe is there better solution without using Subject?
Try using
Observable.Publish
to get anIConnectableObservable<T>
.Output:
Publish
turns the coldScan
observable into a hot observable that begins emitting values whenConnect
is called.