Skip to content

Instantly share code, notes, and snippets.

@rogeralsing
Last active September 15, 2017 14:01
Show Gist options
  • Save rogeralsing/b9280f76e631ec61c831eb4a2256490a to your computer and use it in GitHub Desktop.
Save rogeralsing/b9280f76e631ec61c831eb4a2256490a to your computer and use it in GitHub Desktop.
Reactive Hooks
using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using Starcounter;
namespace StarcounterRx
{
class Program
{
static void Main()
{
Application.Current.Use(new HtmlFromJsonProvider());
Application.Current.Use(new PartialToStandaloneHtmlProvider());
CreateEntitiesInBackground();
Handle.GET("/push", () =>
{
Session.Current = new Session(SessionOptions.PatchVersioning);
var session = Session.Current.SessionId;
var page = new MainPage();
ObservableEntity<DateTimeEntity>
.Inserted
.Where(i => i.Time % 2 == 0)
.Subscribe(e =>
{
Session.ScheduleTask(session, (s, id) =>
{
page.Time = e.Time.ToString();
s.CalculatePatchAndPushOnWebSocket();
});
});
return page;
});
}
private static void CreateEntitiesInBackground()
{
Task.Run(async () =>
{
while (true)
{
await Scheduling.RunTask(() =>
{
Db.Transact(() =>
{
new DateTimeEntity()
{
Time = DateTime.Now.Ticks,
};
});
});
await Task.Delay(1000);
}
});
}
}
public static class ObservableEntity<T>
{
public static Subject<T> Inserted = new Subject<T>();
public static Subject<T> Updated = new Subject<T>();
static ObservableEntity()
{
Hook<T>.CommitInsert += (sender, t) => { Inserted.OnNext(t); };
Hook<T>.CommitUpdate += (sender, t) => { Updated.OnNext(t); };
}
}
[Database]
public class DateTimeEntity
{
public long Time { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment