2
2
using System . Collections . Generic ;
3
3
using System . IO ;
4
4
using System . Linq ;
5
+ using System . Threading ;
6
+ using System . Threading . Tasks ;
5
7
using FaunaDB . Errors ;
6
8
using FaunaDB . Types ;
7
9
8
10
namespace FaunaDB . Client
9
11
{
10
12
public class StreamingEventHandler : IObservable < Value > , IDisposable
11
13
{
14
+ private const int TIME_OUT_IN_MILLIS = 10000 ;
12
15
private readonly List < IObserver < Value > > observers ;
13
16
private StreamReader streamReader ;
17
+ private CancellationTokenSource cancelTokenSource ;
18
+ private Task checkConnectionTask ;
14
19
15
20
private static Field < string > CODE = Field . At ( "event" , "code" ) . To < string > ( ) ;
16
21
private static Field < string > DESCRIPTION = Field . At ( "event" , "description" ) . To < string > ( ) ;
17
22
private static Field < string > TYPE = Field . At ( "type" ) . To < string > ( ) ;
18
23
19
- public StreamingEventHandler ( Stream dataSource )
24
+ public StreamingEventHandler ( Stream dataSource , Func < Task > checkConnection = null )
20
25
{
21
26
dataSource . AssertNotNull ( nameof ( dataSource ) ) ;
22
27
observers = new List < IObserver < Value > > ( ) ;
23
28
streamReader = new StreamReader ( dataSource ) ;
29
+ if ( checkConnection != null )
30
+ {
31
+ cancelTokenSource = new CancellationTokenSource ( ) ;
32
+ CancellationToken token = cancelTokenSource . Token ;
33
+
34
+ checkConnectionTask = Task . Factory . StartNew ( async ( ) =>
35
+ {
36
+ while ( true )
37
+ {
38
+ if ( token . IsCancellationRequested )
39
+ {
40
+ return ;
41
+ }
42
+
43
+ try
44
+ {
45
+ await checkConnection ? . Invoke ( ) ;
46
+ }
47
+ catch ( Exception ex )
48
+ {
49
+ foreach ( var observer in observers . ToList ( ) )
50
+ {
51
+ observer . OnError ( ex ) ;
52
+ }
53
+ }
54
+
55
+ Task . Delay ( TIME_OUT_IN_MILLIS , token ) . Wait ( ) ;
56
+ }
57
+ }
58
+ ) ;
59
+ }
24
60
}
25
61
26
62
public IDisposable Subscribe ( IObserver < Value > observer )
@@ -61,6 +97,15 @@ public async void RequestData()
61
97
62
98
public void Complete ( )
63
99
{
100
+ if ( cancelTokenSource != null )
101
+ {
102
+ cancelTokenSource . Cancel ( ) ;
103
+ if ( ! checkConnectionTask . IsCanceled )
104
+ {
105
+ checkConnectionTask . Wait ( ) ;
106
+ }
107
+ }
108
+
64
109
foreach ( var observer in observers . ToList ( ) )
65
110
{
66
111
observer . OnCompleted ( ) ;
@@ -70,6 +115,10 @@ public void Complete()
70
115
public void Dispose ( )
71
116
{
72
117
streamReader . Dispose ( ) ;
118
+ if ( cancelTokenSource != null )
119
+ {
120
+ cancelTokenSource . Cancel ( ) ;
121
+ }
73
122
}
74
123
75
124
private FaunaException ConstructStreamingException ( Exception ex )
0 commit comments