How to filter one observable with another observable? - unity3d

With https://github.com/neuecc/UniRx,
I have two observables A and B.
I want A to be filtered by B. Sample seems like what I want but the negative of it.
IObservable<long> A = Observable.EveryUpdate();
IObservable<Collider2D> B = this.OnTriggerEnter2DAsObservable()
.Where( x => x.gameObject.tag == "Wall");
I want some kind of Pseudo code like that:
A.filterBy(B)
.Subscribe(x => Debug.Log(x)); //executed only when B is not streaming
(Update1)
Here is actual code. I am trying to cancel out input stream with colliding stream.
var isCollidingWithWall = this.OnTriggerEnter2DAsObservable()
.Where(collider => collider.gameObject.tag == "Wall");
Func<long, float> displaceCalculate = (_) => this.Speed * Time.deltaTime;
var moveLeft = Observable.EveryUpdate()
.Where(_ => Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow));
var moveRight = Observable.EveryUpdate()
.Where(_ => Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow));
var movement1 = moveLeft
.Select(displaceCalculate)
.Select(f => -f);
var movement2 = moveRight
.Select(displaceCalculate);
movement2
.Merge(movement1)
.Subscribe(f =>
{
this.transform.position = new Vector2(this.transform.position.x + f, this.transform.position.y);
});
I think I might be going in wrong direction.

It is difficult to only combine operators.
The two streams are not synchronized.
When the OnNext message comes from stream B, how long shut off stream A?
Next stream B message? or Next stream A?
If you want to stop it only one frame, how about this?
void Start()
{
var isCollisionEntered = false;
this.OnCollisionEnter2DAsObservable()
.Where(x => x.gameObject.tag == "Wall")
.Subscribe(_ => isCollisionEntered = true);
this.LateUpdateAsObservable()
.Where(_ => isCollisionEntered)
.Subscribe(_ => isCollisionEntered = false);
this.UpdateAsObservable()
.Where(_ => !isCollisionEntered)
.Subscribe(_ => Debug.Log("Do here"));
}
And, I don't recommend Observable.EveryUpdate .It is necessary to manage lifetime.
I recommend using this.UpdateAsObservable (UniRx.Triggers) instead.
It automatically publishes OnCompleted message on the gameobject destroyed.

I just came up with another way.
var streamB = this.OnTriggerEnter2DAsObservable().AsUnitObservable();
this.UpdateAsObservable()
.TakeUntil(streamB)
.RepeatUntilDestroy(this)
.Subscribe(_ =>
{
Debug.Log(Time.frameCount);
});

Can you provide a little more context about the actual game behavior you are trying to implement?
My guess would be that there is some other approach to what you are trying to do, without having to rely on EveryUpdate (e.g. by using OnTriggerStay and/or OnTriggerExit).
Just giving a guess to what you mean by "negative" of the sample operator: you might want to have a look at pausable. You'd have to generate the proper boolean values though, and how to do that really depends on what game behavior you are actually trying to implement here.

Related

Efficiently combine many IObservable<bool> streams with boolean operators

I'm looking to combine many IObservable<bool> streams such that when the latest value for all of them is true, a true is emitted, and otherwise a false is emitted.
CombinedLast would allow me to build something like this for two streams easily, but a) I'm not sure the API easily allows thousands of streams to be combined and b) I'm not sure how efficient it would be even if it could.
All is kinda similar to what I want except I'm assuming that works over a single sequence and once false cannot dynamically changes back to true.
Also I need the values to be "distinct until changed", although the DistintUntilChanged operator may not be efficient for this?
I'm hoping for an O(1) algorithm.
A good approach for combining the latest is to start with a IObservable<IObservable<T>> and turn it in to a IObservable<T[]>. This becomes a very dynamic way to combine as many values you need.
Here's an extension method to do this:
public static IObservable<T[]> CombineLatest<T>(this IObservable<IObservable<T>> sources)
{
return
sources.Publish(ss =>
Observable.Create<T[]>(o =>
{
var composite = new CompositeDisposable();
var list = new List<T>();
composite.Add(
ss.Subscribe(source =>
{
var index = list.Count;
list.Add(default(T));
composite.Add(source.Subscribe(x => list[index] = x));
}));
composite.Add(ss.Merge().Select(x => list.ToArray()).Subscribe(o));
return composite;
}));
}
This nicely creates and tracks all subscriptions and uses a closure to define the index that each subscription needs to use to update its value in the list that is used for output.
If you use it like this:
var sources = new Subject<IObservable<bool>>();
var output = sources.CombineLatest();
output.Subscribe(x => Console.WriteLine(x));
var s1 = new Subject<bool>();
sources.OnNext(s1);
s1.OnNext(true);
var s2 = new Subject<bool>();
sources.OnNext(s2);
s2.OnNext(false);
var s3 = new Subject<bool>();
sources.OnNext(s3);
s3.OnNext(true);
s2.OnNext(true);
s1.OnNext(false);
Then you get this output:
If you change the definition of output to var output = sources.CombineLatest().Select(xs => xs.Aggregate((x, y) => x & y)); then you get the output that I think you're after:
True
False
False
True
False
I don't know how to do this in a classically functional way and still achieve O(1). This used mutable state, and is O(1) for observing each message, but O(n) for memory:
public IObservable<bool> CombineBooleans(this IObservable<bool>[] source)
{
return source.Select((o, i) => o.Select(b => (value: b, index: i)))
.Merge()
.Scan((array: new bool[source.Length], countFalse: source.Length), (state, item) =>
{
var countFalse = state.countFalse;
if (state.array[item.index] == item.value)
return (state.array, countFalse); //nothing to change, emit same state
else if (state.array[item.index]) //previous/current state is true, becoming false
{
countFalse++;
state.array[item.index] = false;
}
else //previous/current state is false, becoming true
{
countFalse--;
state.array[item.index] = true;
}
return (state.array, countFalse);
})
.Scan((countFalse: source.Length, oldCountFalse: source.Length), (state, item) => (countFalse: item.countFalse, oldCountFalse: state.countFalse))
.SelectMany(state =>
state.countFalse == 1 && state.oldCountFalse == 0
? Observable.Return(false)
: state.countFalse == 0 && state.oldCountFalse == 1
? Observable.Return(true)
: Observable.Empty<bool>()
)
.Publish()
.RefCount();
}
EDIT: Added .Publish().Refcount() to eliminate multiple-subscriber bugs.

Howto loop OrderedAssertions in FakeItEasy 2

As I understand, ordered assertions in FakeItEasy 2 are done like this (from the docs):
// Assert
A.CallTo(() => unitOfWorkFactory.BeginWork()).MustHaveHappened()
.Then(A.CallTo(() => usefulCollaborator.JustDoIt()).MustHaveHappened())
.Then(A.CallTo(() => unitOfWork.Dispose()).MustHaveHappened());
Now, suppose I have a collection and for each item in this collection I want to assert that a call was made to a faked object. What is the best approach to assert the calls were made in the correct order?
I came up with this, but don't really like it:
IOrderableCallAssertion ioca = null;
foreach (var item in items.OrderBy(i => i.Id)
{
var itemUnderTest = item;
if (ioca == null)
{
ioca = A.CallTo(() => fakeObject.Handle(itemUnderTest, otherArgument)).MustHaveHappened(Repeated.Exactly.Once);
}
else
{
ioca = ioca.Then(A.CallTo(() => fakeObject.Handle(itemUnderTest, otherArgument)).MustHaveHappened(Repeated.Exactly.Once));
}
}
That looks about right to me. Of course, you could inline itemUnderTest and pull MustHaveHappened outside of the two if branches.
And you could always hide this in a convenience method.
An alternative: use Invokes to capture the fakes as the calls come in and later compare them against a list.

Reactive Extension key press media controls

I have a media application that allows the user to Play, Pause, step frame by frame, FastForward, etc. I am attempting to use Rx to get the following behavior for stepping and FastForward.
If the user clicks the right arrow less than 2 times/300ms I want to frame step.
If the user holds down the right arrow I want to fast forward until the right arrow button is released.
I think I have the fast forward part correct, but am not sure how to craft this to get the step functionality. I am also open to "better" ways to do the fast forward.
//start FF when we get 2 key presses within the threshold time
Observable.FromEventPattern<KeyEventArgs>(this, "KeyDown")
.Where(k => k.EventArgs.Key == Key.Right)
.Timestamp()
.Buffer(2)
.Where(x => (x[1].Timestamp - x[0].Timestamp).Milliseconds < 300)
.Subscribe(x =>
{
Console.WriteLine("FastForward GO");
_viewModel.FastForward();
});
//stop ff on the key up
Observable.FromEventPattern<KeyEventArgs>(this, "KeyUp")
.Where(k => k.EventArgs.Key == Key.Right)
.Subscribe(x => {
Console.WriteLine("FastForward STOP");
_viewModel.StopFastForward();
});
Solution
var up = Observable.FromEventPattern<KeyEventArgs>(this, "KeyUp")
.Where(x => x.EventArgs.KeyCode == Keys.Right);
// Take, Concat, and Repeat work together to prevent repeated KeyDown events.
var down = Observable.FromEventPattern<KeyEventArgs>(this, "KeyDown")
.Where(x => x.EventArgs.KeyCode == Keys.Right)
.Take(1)
.Concat(up.Take(1).IgnoreElements())
.Repeat();
var t = TimeSpan.FromMilliseconds(300);
var tap = down.SelectMany(x =>
Observable.Amb(
Observable.Empty<EventPattern<KeyEventArgs>>().Delay(t),
up.Take(1)
))
.Publish()
.RefCount();
var longPress = down.SelectMany(x =>
Observable.Return(x).Delay(t).TakeUntil(tap)
);
There's multiple ways to do this, but this works at getting the "longPress" you need, as well as the "tap". You can use longPress to start fast-fowarding, up to stop fast-forwarding, and tap for frame-stepping.
tap yields when a key has been pressed and released within a timespan of t.
longPress yields when the key has been held down for longer than t.
up yields when the key has been released.
Explaination
A problem exists because the KeyDown event is repeated multiple times for each physical press of a key.
var down = Observable.FromEventPattern<KeyEventArgs>(this, "KeyDown");
In this case, we need a way to filter out the repeated KeyDown events. We can do that by using a combination of operators. First, we'll use Take(1). This will yield the first event and ignore the rest.
var first = down.Take(1);
If we only needed to get a single actual key press, this would be great. But, alas, we need to get all of the actual key presses. We need to wait for the KeyUp event to occur and start the whole thing over. To do this, we can use a combination of Concat and Repeat. For the concat observable, we need to make sure we're only taking 1 up event, and that we're ignore the elements of the up observable, otherwise we end up feeding all of the up events into our new observable.
var down = Observable.FromEventPattern<KeyEventArgs>(this, "KeyDown")
.Take(1)
.Contact(up.Take(1).IgnoreElements())
.Repeat();
This gives us the actual down events, without the in-between repeated events.
Now that we've cleaned up our source observables, we can start composing them in useful ways. What we're looking for is a "tap" event and a "long press" event. To get the tap event, we need to take a single actual down event, and make sure that it isn't held down too long... One way to do this is using the Amb operator.
var tap = down.SelectMany(x =>
Observable.Amb(
Observable.Empty<EventPattern<KeyEventArgs>>().Delay(t),
up.Take(1)
))
The Amb operator stands for "ambiguous". It takes a number of Observables, listens to each one, and waits for them to yield something. Once one of them yields an event, the Amb operator ignores (disposes the subscriptions of) the other observables.
In our case, for each down event that occurs, we use the SelectMany and Amb operator to check to see which yields or completes first... a single up event, or an empty observable that completes after a timespan of t. If the up event occurs before the the empty observable completes, its a tap. Otherwise, we ignore it.
Now we can do a similar thing for "long press", except this time we want to delay the KeyDown event until we know that it's not a tap. We can use a combination of the Delay and TakeUntil operators to do this. Delay makes sure the long press doesn't occur before a tap can be registered, and TakeUntil makes sure we ignore the KeyPress if it turned out to be a tap after all.
var longPress = down.SelectMany(x =>
Observable.Return(x).Delay(t).TakeUntil(tap)
);
Generalized Solution
This version works for any key.
var up = Observable.FromEventPattern<KeyEventArgs>(this, "KeyUp");
var downWithRepeats = Observable.FromEventPattern<KeyEventArgs>(this, "KeyDown");
var down =
Observable.Merge(
up.Select(x => new { e = x, type = "KeyUp" }),
downWithRepeats.Select(x => new { e = x, type = "KeyDown" })
)
.GroupByUntil(
x => x.e.EventArgs.KeyCode,
g => g.Where(y => y.type == "KeyUp")
)
.SelectMany(x => x.FirstAsync())
.Select(x => x.e);
var t = TimeSpan.FromMilliseconds(300);
var tap = down.SelectMany(x =>
Observable.Amb(
Observable.Empty<EventPattern<KeyEventArgs>>().Delay(t),
up.Where(y => y.EventArgs.KeyCode == x.EventArgs.KeyCode).Take(1)
))
.Publish()
.RefCount();
var longPress = down.SelectMany(x =>
Observable.Return(x).Delay(t).TakeUntil(
tap.Where(y => y.EventArgs.KeyCode == x.EventArgs.KeyCode)
)
);
Usage
Observable.Merge(
down .Select(x => string.Format("{0} - press", x.EventArgs.KeyCode)),
tap .Select(x => string.Format("{0} - tap", x.EventArgs.KeyCode)),
longPress.Select(x => string.Format("{0} - longPress", x.EventArgs.KeyCode)),
up .Select(x => string.Format("{0} - up", x.EventArgs.KeyCode))
)
.ObserveOn(SynchronizationContext.Current)
.Select(x => string.Format("{0} - {1}", x, DateTime.Now.ToLongTimeString()))
.Subscribe(text => this.myTextBox.Text = text);
Here's an alternative to Chris's that gives three streams, one for clicks, one for begin holds and one for end holds. Makes use of TimeInterval for recording duration between events.
WinForms Version
We can capture KeyDown eliminating repeats by using GroupByUntil to group KeyDown until a KeyUp occurs:
TimeSpan limit = TimeSpan.FromMilliseconds(300);
var key = Keys.Right;
var keyUp = Observable.FromEventPattern<KeyEventArgs>(this, "KeyUp")
.Where(i => i.EventArgs.KeyCode == key)
.Select(_ => true);
var keyDown = Observable.FromEventPattern<KeyEventArgs>(this, "KeyDown")
.Where(i => i.EventArgs.KeyCode == key)
.GroupByUntil(k => 0, _ => keyUp)
.SelectMany(x => x.FirstAsync());
var keyDownDuration = keyDown.Select(k => keyUp.TimeInterval()).Switch();
var clicks = keyDownDuration.Where(i => i.Interval < limit);
var beginHold = keyDown.Select(k => Observable.Timer(limit).TakeUntil(keyUp))
.Switch();
var endHold = keyDownDuration.Where(i => i.Interval > limit);
/* usage */
clicks.Subscribe(_ => Console.WriteLine("Click"));
beginHold.Subscribe(_ => Console.WriteLine("Hold Begin"));
endHold.Subscribe(_ => Console.WriteLine("Hold End"));
WPF Version
Originally, I had mistakenly assumed the WPF flavour of KevEventArgs as IsRepeat is not available in the WinForms version - which means this won't work for OP, but I'll leave it in as it may be of use for others.
TimeSpan limit = TimeSpan.FromMilliseconds(300);
var key = Key.Right;
var keyUp = Observable.FromEventPattern<KeyEventArgs>(this, "KeyUp")
.Where(i => i.EventArgs.Key == key);
var keyDown = Observable.FromEventPattern<KeyEventArgs>(this, "KeyDown")
.Where(i => i.EventArgs.IsRepeat == false
&& i.EventArgs.Key == key);
var keyDownDuration = keyDown.Select(k => keyUp.TimeInterval()).Switch();
var clicks = keyDownDuration.Where(i => i.Interval < limit);
var beginHold = keyDown.Select(k => Observable.Timer(limit).TakeUntil(keyUp))
.Switch();
var endHold = keyDownDuration.Where(i => i.Interval > limit);
/* usage */
clicks.Subscribe(_ => Console.WriteLine("Click"));
beginHold.Subscribe(_ => Console.WriteLine("Hold Begin"));
endHold.Subscribe(_ => Console.WriteLine("Hold End"));
To Test The Code
Include nuget package rx-main and paste the WinForms/WPF or code snippets as appropriate to the end of the Form contructor. Then run the code and press the right arrow key whilst observing the VS Output window to see the result.

RX PropertyChanged GroupBy deadlock

I am trying to use Reactive Extensions to throttle PropertyChanged notifications. There are examples of doing this using GroupBy, but with one Subscription created for each PropertyName.
I want to handle the PropertyChanged event for all properties, and I need to Throttle those events for each PropertyName.
This is what I have so far, but it causes a deadlock.
ValuesPropertyChanged = Observable.FromEventPattern<PropertyChangedEventArgs>(value, "PropertyChanged")
.GroupBy(o => o.EventArgs.PropertyName)
.First()
.Throttle(TimeSpan.FromSeconds(2))
.Subscribe(args => HandlePropertyChanged(args.EventArgs.PropertyName));
The deadlock happens in the call to .First().
It still locks if I change that line to:
.Select(o => o.First())
I have also tried
.Select(o => o.FirstAsync())
The examples for GroupBy here look pretty concise, but I am incapable of wrapping my head around converting these examples to my solution.
Why does this cause a deadlock, and what should I do to make this work?
I think this might be what you're after:
// assume MyObj : INotifyPropertyChanged, naturally
var value = new MyObj();
Action<string> HandlePropertyChanged =
name => Console.WriteLine("Got a change for name:" + name);
// The query
var valuesPropertyChanged =
// create from event stream
from propChange in Observable.FromEventPattern<PropertyChangedEventArgs>(
value,
"PropertyChanged")
// group events by property name
group propChange by propChange.EventArgs.PropertyName into batchByName
// Throttle the resulting batch
from throttledByName in batchByName.Throttle(TimeSpan.FromSeconds(1))
// then select each item of the "throttled output"
select throttledByName;
valuesPropertyChanged.Subscribe(args =>
HandlePropertyChanged(args.EventArgs.PropertyName));
for(int i=0;i<10;i++)
{
value.Value1 = i.ToString();
value.Value2 = (i-1).ToString();
}
Output:
Got a change for name:Value2
Got a change for name:Value1
Here is the same but with extension methods:
var valuesPropertyChanged =
Observable.FromEventPattern<PropertyChangedEventArgs>(
_vm,
"PropertyChanged")
.GroupBy(propchange => propchange.EventArgs.PropertyName)
.Select(o => o.Throttle(TimeSpan.FromSeconds(1)))
.Merge();

Reactive Framework / DoubleClick

I know that there is an easy way to do this - but it has beaten me tonight ...
I want to know if two events occur within 300 milliseconds of each other, as in a double click.
Two leftdown mouse clicks in 300 milliseconds - I know this is what the reactive framework was built for - but damn if I can find a good doc that has simple examples for all the extenstion operatores - Throttle, BufferWithCount, BufferWithTime - all of which just werent' doing it for me....
The TimeInterval method will give you the time between values.
public static IObservable<Unit> DoubleClicks<TSource>(
this IObservable<TSource> source, TimeSpan doubleClickSpeed, IScheduler scheduler)
{
return source
.TimeInterval(scheduler)
.Skip(1)
.Where(interval => interval.Interval <= doubleClickSpeed)
.RemoveTimeInterval();
}
If you want to be sure that triple clicks don't trigger values, you could just use Repeat on a hot observable (I've used a FastSubject here as the clicks will all come on one thread and therefore don't require the heaviness of the normal Subjects):
public static IObservable<TSource> DoubleClicks<TSource>(
this IObservable<TSource> source, TimeSpan doubleClickSpeed, IScheduler scheduler)
{
return source.Multicast<TSource, TSource, TSource>(
() => new FastSubject<TSource>(), // events won't be multithreaded
values =>
{
return values
.TimeInterval(scheduler)
.Skip(1)
.Where(interval => interval.Interval <= doubleClickSpeed)
.RemoveTimeInterval()
.Take(1)
.Repeat();
});
}
Edit - Use TimeInterval() instead.
The Zip() and Timestamp() operators might be a good start.
var ioClicks = Observable.FromEvent<MouseButtonEventHandler, RoutedEventArgs>(
h => new MouseButtonEventHandler(h),
h => btn.MouseLeftButtonDown += h,
h => btn.MouseLeftButtonDown -= h);
var ioTSClicks = ioClicks.Timestamp();
var iodblClicks = ioTSClicks.Zip(ioTSClicks.Skip(1),
(r, l) => l.Timestamp - r.Timestamp)
.Where(tspan => tspan.TotalMilliseconds < 300);
Probably best to test this via the test scheduler, so you know exactly what you're getting:
[Fact]
public void DblClick()
{
// setup
var ioClicks = _scheduler.CreateHotObservable(
OnNext(210, "click"),
OnNext(220, "click"),
OnNext(300, "click"),
OnNext(365, "click"))
.Timestamp(_scheduler);
// act
Func<IObservable<TimeSpan>> target =
() => ioClicks.Zip(ioClicks.Skip(1),
(r, l) => l.Timestamp - r.Timestamp)
.Where(tspan => tspan.Ticks < 30);
var actuals = _scheduler.Run(target);
// assert
Assert.Equal(actuals.Count(), 1);
// + more
}
public static Recorded<Notification<T>> OnNext<T>(long ticks, T value)
{
return new Recorded<Notification<T>>(
ticks,
new Notification<T>.OnNext(value));
}