-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathStateMachine.ObserverTransitionState.cs
65 lines (55 loc) · 2.04 KB
/
StateMachine.ObserverTransitionState.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
namespace BAStudio.StatePattern
{
public partial class StateMachine<T>
{
public abstract class ObserverTransitionState<H, FROM, TO> : State, IObserver<H> where FROM : State where TO : State, new()
{
IDisposable handle;
TO instancedNext;
object parameter;
public ObserverTransitionState(IObservable<H> observable, TO instance = null, object parameter = null)
{
handle = observable.Subscribe(this);
instancedNext = instance;
this.parameter = parameter;
}
public override void OnEntered(StateMachine<T> machine, State previous, T subject, object parameter = null)
{
if (typeof(FROM) != previous.GetType()) throw new InvalidOperationException("Transition source state mismatch");
// Reset
isCompleted = false;
exception = null;
progress = default(H);
}
public override void OnLeaving(StateMachine<T> machine, State next, T subject, object parameter = null)
{
handle.Dispose();
}
public override void Update(StateMachine<T> machine, T subject)
{
if (isCompleted)
{
if (instancedNext != null) machine.ChangeState(instancedNext, parameter);
else machine.ChangeState<TO>(parameter);
}
else if (exception != null) { /* DEBUG OUTPUT */ }
}
bool isCompleted;
Exception exception;
H progress;
public virtual void OnCompleted()
{
isCompleted = true; // Because we don't know which thread it is
}
public virtual void OnNext(H value)
{
progress = value;
}
public virtual void OnError(Exception error)
{
exception = error;
}
}
}
}