forked from reactiveui/ReactiveUI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAndroidUIScheduler.cs
More file actions
80 lines (66 loc) · 2.54 KB
/
AndroidUIScheduler.cs
File metadata and controls
80 lines (66 loc) · 2.54 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
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using ReactiveUI;
using Android.App;
using Splat;
using Android.OS;
namespace ReactiveUI
{
/// <summary>
/// HandlerScheduler is a scheduler that schedules items on a running
/// Activity's main thread. This is the moral equivalent of
/// DispatcherScheduler.
public class HandlerScheduler : IScheduler, IEnableLogger
{
public static IScheduler MainThreadScheduler = new HandlerScheduler(new Handler(Looper.MainLooper), Looper.MainLooper.Thread.Id);
Handler handler;
long looperId;
public HandlerScheduler(Handler handler, long? threadIdAssociatedWithHandler)
{
this.handler = handler;
looperId = threadIdAssociatedWithHandler ?? -1;
}
public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
bool isCancelled = false;
var innerDisp = new SerialDisposable() { Disposable = Disposable.Empty };
if (looperId > 0 && looperId == Java.Lang.Thread.CurrentThread().Id) {
return action(this, state);
}
handler.Post(() => {
if (isCancelled) return;
innerDisp.Disposable = action(this, state);
});
return new CompositeDisposable(
Disposable.Create(() => isCancelled = true),
innerDisp);
}
public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
bool isCancelled = false;
var innerDisp = new SerialDisposable() { Disposable = Disposable.Empty };
handler.PostDelayed(() => {
if (isCancelled) return;
innerDisp.Disposable = action(this, state);
}, dueTime.Ticks / 10 / 1000);
return new CompositeDisposable(
Disposable.Create(() => isCancelled = true),
innerDisp);
}
public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
{
if (dueTime <= Now) {
return Schedule(state, action);
}
return Schedule(state, dueTime - Now, action);
}
public DateTimeOffset Now {
get { return DateTimeOffset.Now; }
}
}
}
// vim: tw=120 ts=4 sw=4 et :