Here I have simple code written in C#.
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Reactive.Subjects;
namespace ReactiveProgramming
{
class Program
{
static void Main(string[] args)
{
var generateSeq = new GenerateSequence();
Console.WriteLine("Hello World!");
generateSeq.Sequence.Subscribe(val =>
{
Console.WriteLine(val);
// it works if I remove below two lines ...
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r");
});
generateSeq.Run();
}
}
class GenerateSequence
{
public Subject<int> Sequence = new Subject<int>();
public void Run(int runTimes = 10)
{
ConsoleKeyInfo cki;
Task.Run(() => runForTimes(10));
do
{
cki = Console.ReadKey();
} while (cki.Key != ConsoleKey.Escape);
}
public void runForTimes(int runTimes = 10)
{
for (var i = 0; i < 10; i++)
{
Sequence.OnNext(i);
Thread.Sleep(1000);
}
}
}
}
But instead of printing sequence on top of each other, it just freeze the output after first emit.
And tested in Linux too ... same output.
If I remote these lines Console.SetCursorPosition
and Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r")
from subscribe ... it works and print all numbers on screen one after another but I want to print on top of each other ...
But if I change my Main function like this:
static void Main(string[] args)
{
var generateSeq = new GenerateSequence();
Console.WriteLine("Hello World!");
generateSeq.Sequence.Subscribe(val =>
{
Console.WriteLine(val);
// Console.SetCursorPosition(0, Console.CursorTop - 1);
// Console.Write("\r" + new string(' ', Console.WindowWidth) + "\r");
});
generateSeq.Run();
}
Where I have commented those two lines ... output is as follows ...
But instead of output in sequence like second image, I want to print the output at the same position. Just over write the new output over the old one
Note: I am running it on Macbook Pro (Big Sur), it happens with .net core 3.1 or .net 5.0 and using iTerm as console emulator