Skip to content

Instantly share code, notes, and snippets.

@panesofglass
Created December 4, 2009 05:01
Show Gist options
  • Select an option

  • Save panesofglass/248845 to your computer and use it in GitHub Desktop.

Select an option

Save panesofglass/248845 to your computer and use it in GitHub Desktop.
Call/CC in Rx
using System;
using System.Collections.Generic;
using System.Linq;
namespace CallCC
{
/// <summary>An attempt to understand Call/CC in Rx</summary>
class Program
{
static void Main(string[] args)
{
// Imperative
Console.WriteLine("Starting imperative sample...\n\n");
Console.WriteLine("Really delete?");
var response = Console.ReadLine() ?? "NO";
if (response.ToUpperInvariant() == "YES")
Console.WriteLine("Deleted!");
else
Console.WriteLine("Deleted action aborted.");
Console.ReadLine();
// CPS
Console.WriteLine("\n\nStarting CPS sample...\n\n");
var cpsDisposable =
new YesNoMessage("Really delete?").Render()
.Subscribe(result =>
{
if (result)
new InfoMessage("Deleted!").Render();
else
new InfoMessage("Deleted action aborted.").Render();
});
cpsDisposable.Dispose();
Console.ReadKey();
// Call/CC 1
Console.WriteLine("\n\nStarting Call/CC sample...\n\n");
if (Observable.Create<bool>(o => new YesNoMessage("Really delete?").Render().Subscribe(o).Dispose).NextValue().Get())
Observable.Create<bool>(o => new InfoMessage("Deleted!").Render().Subscribe(o).Dispose);
else
Observable.Create<bool>(o => new InfoMessage("Deleted action aborted.").Render().Subscribe(o).Dispose);
Console.ReadKey();
}
}
class InfoMessage
{
protected readonly string _message;
public InfoMessage(string message)
{
_message = message;
}
public virtual IObservable<bool> Render()
{
Console.WriteLine(_message);
return UserResponses().ToObservable()
.Select(response => true);
}
protected IEnumerable<string> UserResponses()
{
while(true)
{
yield return Console.ReadLine();
}
}
}
class YesNoMessage : InfoMessage
{
public YesNoMessage(string message) : base(message)
{
}
public override IObservable<bool> Render()
{
Console.WriteLine(_message);
return UserResponses().ToObservable()
.Select(response => response.ToUpperInvariant() == "YES" ? true : false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment