Permalink
Browse files

TextConsole - extract input loop into InputLoop

  • Loading branch information...
bobbymcr committed Dec 4, 2018
1 parent 44de275 commit 590a13cded904481c055cf969c128c151c98ea1b
Showing with 39 additions and 18 deletions.
  1. +39 −18 core/src/TextConsole.cs
@@ -23,38 +23,59 @@ public TextConsole(MessageBus bus, TextReader reader, TextWriter writer)

public void Run(CancellationToken token)
{
using (this.bus.Subscribe<OutputMessage>(m => this.writer.WriteLine(m.Text)))
using (InputLoop loop = new InputLoop(this.bus, this.ReadLine, m => this.writer.WriteLine(m.Text)))
{
loop.Run(token);
}
}

private bool ReadLine()
{
string line = this.reader.ReadLine();
if (line == null)
{
return false;
}

this.bus.Send(new InputMessage(line));
return true;
}

private sealed class InputLoop : IDisposable
{
private readonly Func<bool> readInput;
private readonly IDisposable sub;

public InputLoop(MessageBus bus, Func<bool> readInput, Action<OutputMessage> onOutput)
{
this.readInput = readInput;
this.sub = bus.Subscribe(onOutput);
}

public void Run(CancellationToken token)
{
try
{
this.ReadLines(token);
this.RunInner(token);
}
catch (OperationCanceledException)
{
}
}
}

private void ReadLines(CancellationToken token)
{
string line;
do
public void Dispose()
{
line = this.ReadLine(token);
this.sub.Dispose();
}
while (line != null);
}

private string ReadLine(CancellationToken token)
{
token.ThrowIfCancellationRequested();
string line = this.reader.ReadLine();
if (line != null)
private void RunInner(CancellationToken token)
{
this.bus.Send(new InputMessage(line));
do
{
token.ThrowIfCancellationRequested();
}
while (this.readInput());
}

return line;
}
}
}

0 comments on commit 590a13c

Please sign in to comment.