/
PusherHelper.cs
51 lines (43 loc) · 1.63 KB
/
PusherHelper.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using PusherClientDotNet;
using ReactiveUI;
namespace Play.Models
{
public static class PusherHelper
{
public static IObservable<T> Connect<T>(Func<Pusher> pusherFactory, string channel, string eventName)
{
var pusher = pusherFactory();
var disp = new CompositeDisposable();
return Observable.Create<T>(subj => {
bool hasCompleted = false;
try {
pusher.Connect();
disp.Add(Disposable.Create(pusher.Disconnect));
// NB: Pusher is racey, give it some time to connect
var postConnect = Observable.Start(() => {
var ch = pusher.Subscribe(channel);
disp.Add(Disposable.Create(() => pusher.Unsubscribe(channel)));
ch.Bind(eventName, x => {
if (hasCompleted) return;
subj.OnNext((T) x);
});
disp.Add(Disposable.Create(ch.Disconnect));
}, RxApp.TaskpoolScheduler);
postConnect.Subscribe(_ => { },
ex => LogHost.Default.WarnException("Couldn't connect to Pusher", ex));
} catch (Exception ex) {
subj.OnError(ex);
hasCompleted = true;
}
return disp;
});
}
}
}