Skip to content

Instantly share code, notes, and snippets.

@Clancey
Last active August 5, 2020 03:36
Show Gist options
  • Save Clancey/db9f4e3550488cfc08aa6420ad1f8505 to your computer and use it in GitHub Desktop.
Save Clancey/db9f4e3550488cfc08aa6420ad1f8505 to your computer and use it in GitHub Desktop.
//This uses Records to make the code smaller, even though it doesnt come out until C# 9
//IT also uses a new abstract class, that shouldnt count against it's line count: https://gist.github.com/Clancey/1df421c93ee20832d793a96b30fec997
public data class Model
{
public int Count { get; set; }
public int Step { get; set; }
public bool TimerOn { get; set; }
}
public enum Msg
{
Incrament,
Decrament,
Reset,
SetStep,
TimerToggled,
TimedTick,
TickTimer
}
public class StatefulMVUSample : StatefulView<Tuple<Msg, object>, Model>
{
public StatefulMVUSample() : base(new Model { Count = 0, Step = 1, TimerOn = false })
{
}
public override Model Update(Tuple<Msg, object> message, Model model)
{
switch (message.Item1)
{
case Msg.Incrament:
return model with { Count = model.Count + model.Step };
case Msg.Decrament:
return model with { Count = model.Count - model.Step };
case Msg.Reset:
return init();
case Msg.SetStep:
return model with { Step = (int)message.Item2 };
case Msg.TimerToggled:
var newModel = model with { TimerOn = (bool)message.Item2 };
if (newModel.TimerOn)
TickTimer();
return newModel;
case Msg.TimedTick:
var newModel = model.TimerOn ? model with { Count = model.Count + model.Step } : model;
if (newModel.TimerOn)
TickTimer();
return newModel;
default:
return model;
}
}
public override View View(Model model) =>
new VStack
{
new Text($"{model.Count}"),
new Button("Increment",()=> Dispatch(new Tuple<Msg,object>(Msg.Incrament,null))),
new Button("Decrement",()=> Dispatch(new Tuple<Msg,object>(Msg.Decrament,null))),
new HStack
{
new Text("Timer"),
new Toggle(model.TimerOn,(value)=> Dispatch(new Tuple<Msg,object>(Msg.TimerToggled,value)))
},
new Slider(model.Step,through:10,onEditingChanged: (value) => Dispatch(new Tuple<Msg, object>(Msg.SetStep,value))),
new Text($"Step Size: {model.Step}"),
new Button("Reset", ()=> Dispatch(new Tuple<Msg, object>(Msg.Reset,null)))
};
Model init() => new Model { Count = 0, Step = 1, TimerOn = false };
async void TickTimer() {
await Task.Delay(200);
Dispatch(new Tuple<Msg, object>(Msg.TimedTick,null));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment