Skip to content

Commit

Permalink
Added Scheduler for Terminal (#103)
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisPulman authored Jul 29, 2024
1 parent a2ecc6c commit 854c05f
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/ReactiveMvvm.Terminal/Program.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Reactive.Concurrency;
using ReactiveMvvm.Services;
using ReactiveMvvm.Terminal.Services;
using ReactiveMvvm.Terminal.Views;
using ReactiveMvvm.ViewModels;
using ReactiveUI;
using Terminal.Gui;

namespace ReactiveMvvm.Terminal
Expand All @@ -12,6 +14,8 @@ public static class Program
public static void Main(string[] args)
{
Application.Init();
RxApp.MainThreadScheduler = TerminalScheduler.Default;
RxApp.TaskpoolScheduler = TaskPoolScheduler.Default;
Application.Run(
new FeedbackView(
new(
Expand Down
60 changes: 60 additions & 0 deletions src/ReactiveMvvm.Terminal/TerminalScheduler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using Terminal.Gui;

namespace ReactiveMvvm;

public class TerminalScheduler : LocalScheduler
{
public static readonly TerminalScheduler Default = new ();
private TerminalScheduler () { }

public override IDisposable Schedule<TState> (
TState state,
TimeSpan dueTime,
Func<IScheduler, TState, IDisposable> action
)
{
IDisposable PostOnMainLoop ()
{
var composite = new CompositeDisposable (2);
var cancellation = new CancellationDisposable ();

Application.Invoke (
() =>
{
if (!cancellation.Token.IsCancellationRequested)
{
composite.Add (action (this, state));
}
}
);
composite.Add (cancellation);

return composite;
}

IDisposable PostOnMainLoopAsTimeout ()
{
var composite = new CompositeDisposable (2);

object timeout = Application.AddTimeout (
dueTime,
() =>
{
composite.Add (action (this, state));

return false;
}
);
composite.Add (Disposable.Create (() => Application.RemoveTimeout (timeout)));

return composite;
}

return dueTime == TimeSpan.Zero
? PostOnMainLoop ()
: PostOnMainLoopAsTimeout ();
}
}

0 comments on commit 854c05f

Please sign in to comment.