mercredi 8 avril 2015

Switch vs SelectMany + TakeUntil


Vote count:

0




I'm writing an operator that effectively does the same as Switch plus some other stuff. I always understood Switch to effectively be a neat wrapper around SelectMany combined with TakeUntil. However whilst implementing my new extension I've noticed something different about the order of creation/disposal of inner sequences. I'm wondering how I can replicate the order Switch works in since it seems likely we'd always want to dispose the existing inner before creating a new one.


I've written 2 tests to illustrate what I mean.


StandardSwitch will give the following output: Disposing Inner followed by Creating New Inner


HandCrankedSwitch will give: Creating New Inner, Disposing Inner


See example code below:



[TestMethod]
public void StandardSwitch()
{
var outer = Observable.Interval(TimeSpan.FromSeconds(1))
.Do(x => Console.WriteLine("New Outer Value is {0}", x));

var wait = new CountdownEvent(8);

outer
.Select(CreateInner)
.Switch()
.Subscribe(x =>
{
Console.WriteLine("Subscriber Got {0}", x);
wait.Signal();
});

wait.Wait();

Console.WriteLine("Done");
}

[TestMethod]
public void HandCrankedSwitch()
{
var outer = Observable.Interval(TimeSpan.FromSeconds(1))
.Do(x => Console.WriteLine("New Outer Value is {0}", x));

var wait = new CountdownEvent(8);

outer.Publish(x => x.Select(CreateInner).SelectMany(xs => xs.TakeUntil(x)))
.Subscribe(x =>
{
Console.WriteLine("Subscriber Got {0}", x);
wait.Signal();
});

wait.Wait();

Console.WriteLine("Done");
}
internal IObservable<long> CreateInner(long notUsed)
{
return Observable.Create<long>(obs =>
{
Console.WriteLine("Creating New Inner");

var compDis = new CompositeDisposable {Disposable.Create(() => Console.WriteLine("Disposing Inner"))};

var dis = Observable.Interval(TimeSpan.FromSeconds(0.4))
.Do(x => Console.WriteLine("New Inner Value is {0}", x))
.Subscribe(obs);

compDis.Add(dis);

return compDis;
});
}


asked 2 mins ago







Switch vs SelectMany + TakeUntil

Aucun commentaire:

Enregistrer un commentaire