-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStateMachine.ObserverTransitionState.cs
More file actions
69 lines (59 loc) · 2.17 KB
/
StateMachine.ObserverTransitionState.cs
File metadata and controls
69 lines (59 loc) · 2.17 KB
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
66
67
68
69
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;
private readonly IObservable<H>? observable;
TO instancedNext;
object parameter;
public ObserverTransitionState(IObservable<H> observable, TO instance = null, object parameter = null)
{
this.observable = observable;
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);
handle = observable?.Subscribe(this);
}
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) {
throw exception;
}
}
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;
}
}
}
}