forked from reactiveui/ReactiveUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeolocation.cs
More file actions
207 lines (178 loc) · 7.73 KB
/
Geolocation.cs
File metadata and controls
207 lines (178 loc) · 7.73 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
using Splat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reactive.Threading.Tasks;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Geolocation;
#if ANDROID
using AndroidApp = Android.App.Application;
#endif
namespace ReactiveUI.Mobile
{
/// <summary>
/// ReactiveGeolocator is an API to convert Xamarin Geolocation into
/// something Rx-friendly.
/// </summary>
public static class ReactiveGeolocator
{
[ThreadStatic] static IReactiveGeolocator _UnitTestImplementation;
static IReactiveGeolocator _Implementation;
internal static IReactiveGeolocator Implementation {
get { return _UnitTestImplementation ?? _Implementation; }
set {
if (ModeDetector.InUnitTestRunner()) {
_UnitTestImplementation = value;
_Implementation = _Implementation ?? value;
} else {
_Implementation = value;
}
}
}
/// <summary>
/// Returns an IObservable that continuously updates as the user's
/// physical location changes. It is super important to make sure to
/// dispose all subscriptions to this IObservable.
/// </summary>
/// <param name="minUpdateTime">Minimum update time.</param>
/// <param name="minUpdateDist">Minimum update dist.</param>
/// <param name="includeHeading">If set to <c>true</c> include heading.</param>
public static IObservable<Position> Listen(int minUpdateTime, double minUpdateDist, bool includeHeading = false)
{
if (Implementation != null) {
return Implementation.Listen(minUpdateTime, minUpdateDist, includeHeading);
}
var ret = Observable.Create<Position>(subj => {
#if ANDROID
var geo = new Geolocator(AndroidApp.Context);
#else
var geo = new Geolocator();
#endif
var disp = new CompositeDisposable();
bool isDead = false;
if (!geo.IsGeolocationAvailable || !geo.IsGeolocationEnabled) {
return Observable.Throw<Position>(new Exception("Geolocation isn't available")).Subscribe(subj);
}
// NB: This isn't very Functional, but I'm lazy.
disp.Add(Observable.FromEventPattern<PositionEventArgs>(x => geo.PositionChanged += x, x => geo.PositionChanged -= x).Subscribe(x => {
if (isDead) return;
subj.OnNext(x.EventArgs.Position);
}));
disp.Add(Observable.FromEventPattern<PositionErrorEventArgs>(x => geo.PositionError += x, x => geo.PositionError -= x).Subscribe(ex => {
isDead = true;
var toDisp = Interlocked.Exchange(ref disp, null);
if (toDisp != null) toDisp.Dispose();
subj.OnError(new GeolocationException(ex.EventArgs.Error));
}));
return disp;
});
return ret.Multicast(new Subject<Position>()).RefCount();
}
/// <summary>
/// Returns a single lookup of the user's current physical position
/// </summary>
/// <returns>The current physical location.</returns>
/// <param name="includeHeading">If set to <c>true</c> include heading.</param>
public static IObservable<Position> GetPosition(bool includeHeading = false)
{
if (Implementation != null) {
return Implementation.GetPosition(includeHeading);
}
#if !WP7 && !WP8
var ret = Observable.Create<Position>(subj => {
#if ANDROID
var geo = new Geolocator(AndroidApp.Context);
#else
var geo = new Geolocator();
#endif
var cts = new CancellationTokenSource();
var disp = new CompositeDisposable();
if (!geo.IsGeolocationAvailable || !geo.IsGeolocationEnabled) {
return Observable.Throw<Position>(new Exception("Geolocation isn't available")).Subscribe(subj);
}
disp.Add(new CancellationDisposable(cts));
disp.Add(geo.GetPositionAsync(cts.Token, includeHeading).ToObservable().Subscribe(subj));
return disp;
}).Multicast(new AsyncSubject<Position>());
#else
// NB: Xamarin.Mobile.dll references CancellationTokenSource, but
// the one we have comes from the BCL Async library - if we try to
// pass in our type into the Xamarin library, it gets confused.
var ret = Observable.Create<Position>(subj => {
var geo = new Geolocator();
var disp = new CompositeDisposable();
if (!geo.IsGeolocationAvailable || !geo.IsGeolocationEnabled) {
return Observable.Throw<Position>(new Exception("Geolocation isn't available")).Subscribe(subj);
}
disp.Add(geo.GetPositionAsync(Int32.MaxValue, includeHeading).ToObservable().Subscribe(subj));
return disp;
}).Multicast(new AsyncSubject<Position>());
#endif
return ret.RefCount();
}
public static IDisposable WithGeolocator(IReactiveGeolocator implementation)
{
var orig = Implementation;
Implementation = implementation;
return Disposable.Create(() => Implementation = orig);
}
public static IDisposable UseLocationData(IObservable<Position> positionStream, IScheduler scheduler = null)
{
return WithGeolocator(new TestGeolocator(positionStream, scheduler));
}
}
public class TestGeolocator : IReactiveGeolocator
{
readonly BehaviorSubject<Position> _latestPosition = new BehaviorSubject<Position>(null);
readonly IScheduler _scheduler;
public TestGeolocator(IObservable<Position> positionStream, IScheduler scheduler = null)
{
positionStream.Multicast(_latestPosition).Connect();
_scheduler = scheduler ?? RxApp.MainThreadScheduler;
}
public IObservable<Position> Listen(int minUpdateTime, double minUpdateDist, bool includeHeading = false)
{
DateTimeOffset? lastStamp = null;
Position lastPos = null;
return _latestPosition.Skip(1)
.Timestamp(_scheduler)
.Where(x => {
var ret = lastStamp == null || x.Timestamp - lastStamp > TimeSpan.FromMilliseconds(minUpdateTime);
lastStamp = x.Timestamp;
return ret;
})
.Where(x => {
var ret = lastPos == null || distForPos(lastPos, x.Value) > minUpdateDist;
lastPos = x.Value;
return ret;
})
.Select(x => x.Value);
}
public IObservable<Position> GetPosition(bool includeHeading = false)
{
var ret = _latestPosition.Take(1).Multicast(new AsyncSubject<Position>());
ret.Connect();
return ret;
}
double distForPos(Position lhs, Position rhs)
{
return Math.Sqrt(
Math.Pow(rhs.Latitude - lhs.Latitude, 2.0) +
Math.Pow(rhs.Longitude - lhs.Longitude, 2.0));
}
}
public class GeolocationException : Exception
{
public GeolocationException(GeolocationError error)
{
Info = error;
}
public GeolocationError Info { get; protected set; }
}
}