19
19
import java .util .PriorityQueue ;
20
20
import java .util .Queue ;
21
21
import java .util .concurrent .TimeUnit ;
22
+ import java .util .concurrent .atomic .AtomicBoolean ;
22
23
23
24
import rx .Scheduler ;
24
25
import rx .Subscription ;
25
- import rx .subscriptions .Subscriptions ;
26
26
import rx .util .functions .Func2 ;
27
27
28
28
public class TestScheduler extends Scheduler {
29
29
private final Queue <TimedAction <?>> queue = new PriorityQueue <TimedAction <?>>(11 , new CompareActionsByTime ());
30
30
31
31
private static class TimedAction <T > {
32
+
32
33
private final long time ;
33
34
private final Func2 <Scheduler , T , Subscription > action ;
34
35
private final T state ;
35
36
private final TestScheduler scheduler ;
37
+ private final AtomicBoolean isCancelled = new AtomicBoolean (false );
36
38
37
39
private TimedAction (TestScheduler scheduler , long time , Func2 <Scheduler , T , Subscription > action , T state ) {
38
40
this .time = time ;
@@ -41,6 +43,10 @@ private TimedAction(TestScheduler scheduler, long time, Func2<Scheduler, T, Subs
41
43
this .scheduler = scheduler ;
42
44
}
43
45
46
+ public void cancel () {
47
+ isCancelled .set (true );
48
+ }
49
+
44
50
@ Override
45
51
public String toString () {
46
52
return String .format ("TimedAction(time = %d, action = %s)" , time , action .toString ());
@@ -85,8 +91,12 @@ private void triggerActions(long targetTimeInNanos) {
85
91
}
86
92
time = current .time ;
87
93
queue .remove ();
88
- // because the queue can have wildcards we have to ignore the type T for the state
89
- ((Func2 <Scheduler , Object , Subscription >) current .action ).call (current .scheduler , current .state );
94
+
95
+ // Only execute if the TimedAction has not yet been cancelled
96
+ if (!current .isCancelled .get ()) {
97
+ // because the queue can have wildcards we have to ignore the type T for the state
98
+ ((Func2 <Scheduler , Object , Subscription >) current .action ).call (current .scheduler , current .state );
99
+ }
90
100
}
91
101
}
92
102
@@ -97,7 +107,14 @@ public <T> Subscription schedule(T state, Func2<Scheduler, T, Subscription> acti
97
107
98
108
@ Override
99
109
public <T > Subscription schedule (T state , Func2 <Scheduler , T , Subscription > action , long delayTime , TimeUnit unit ) {
100
- queue .add (new TimedAction <T >(this , time + unit .toNanos (delayTime ), action , state ));
101
- return Subscriptions .empty ();
110
+ final TimedAction <T > timedAction = new TimedAction <T >(this , time + unit .toNanos (delayTime ), action , state );
111
+ queue .add (timedAction );
112
+
113
+ return new Subscription () {
114
+ @ Override
115
+ public void unsubscribe () {
116
+ timedAction .cancel ();
117
+ }
118
+ };
102
119
}
103
120
}
0 commit comments