How I could convert the MainEngine Observable to Cold ? from this example:
public IObservable<int> MainEngine
{
get
{
Random rnd = new Random();
int maxValue = rnd.Next(20);
System.Diagnostics.Trace.TraceInformation("Max value is: " + maxValue.ToString());
return (from sinlgeInt in Enumerable.Range(0, maxValue)
select sinlgeInt).ToObservable();
}
}
public void Main()
{
// 1
MainEngine.Subscribe(
onNext: (item) => { System.Diagnostics.Trace.TraceInformation("Value is: " + item.ToString()); }
);
// 2
MainEngine.Subscribe(
onNext: (item) => { System.Diagnostics.Trace.TraceInformation("Gonna put it into XML: " + item.ToString()); }
);
}
Question 1: On subscriber 1 and subscriber 2 I get a different results but I want both of them receive the same results.
Question 2: From the point in time when I add the second subscriber both of them continue to receive the same results.
Regarding your first question, the issue is that the observers are not subscribing to the same
IObservablesince you call the getter twice.Assigning the
IObservableto a local variable seems to fix the issue:Regarding your second question, if you would like to share a subcription to a single
IObservable, you can use thePublishmethod:The two subscribers will then see the results from the
IObservablein an interleaved fashion:You can also subscribe new observers after the call to Subscribe, after which point all subscribers will see the same events. You can modify your example to test this, by running your observable on a new thread and introducing a delay:
You will see one second’s worth of events only on the first observer, and then both observers will see each event simultaneously.