Presentations from the june meeting of IDNDUG
http://ariely.info/Communities/IDNDUG/IDNDUG19thJune2013/tabid/171
The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Using Rx, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, andparameterize the concurrency in the asynchronous data streams using Schedulers. Simply put, Rx = Observables + LINQ + Schedulers
2. About Me
•
•
•
•
•
Software architect, consultant and instructor
Technology addict
10 years of experience
.NET and Native Windows Programming
http://www.TamirDresher.com.
12. Converting Events and Asynchronous Methods
// Convert the TextChanged event to IObservable<string>
var input = (from evt in Observable.FromEventPattern(txt, “TextChanged”)
select ((TextBox)evt.Sender).Text)
.Throttle(TimeSpan.FromSeconds(0.5))
.DistinctUntilChanged();
// Convert asynchronous proxy methods to Func<string, IObservable<string[]>>
var lookup = Observable.FromAsyncPattern<string, string[]>(svc.BeginLookup,
svc.EndLookup);
// Compose both sources using a query
var res = from term in input
from words in lookup(term).TakeUntil(input)
select words;
18. Stock Trade Analysis
MSFT
27.01
INTC
21.75
MSFT
27.96
MSFT
31.21
INTC
22.54
Company = MSFT
Increase = 0.104
from tick in ticks
group tick by tick.Symbol into company
from openClose in company.Buffer(2, 1)
let diff = (openClose[1] – openClose[0]) / openClose[0]
where diff > 0.1
select new { Company = company.Key, Increase = diff }
INTC
20.98
MSFT
30.73
20. The Role of Schedulers
Parameterize Concurrency
//
// Runs a timer on the default scheduler
//
IObservable long
TimeSpan
//
// Every operator that introduces concurrency
// has an overload with an IScheduler
//
IObservable long
TimeSpan
IScheduler scheduler
21. The Role of Schedulers
var
Observable.Return
Scheduler.ThreadPool
"Answer = "
xs.ObserveOn(
frm )
xs.ObserveOn(new ControlScheduler(frm))
.Subscribe(x => lbl.Text = "Answer = " + x);
23. Operational Layering of Rx
public static IObservable<T> Return<T>(T value,
IScheduler scheduler)
{
return Observable.Create<T>(observer =>
{
// Serialize state to scheduler; return ability to cancel
return scheduler.Schedule(new { value, observer }, (_, x) =>
{
x.observer.OnNext(x.value);
x.observer.OnCompleted();
return Disposable.Empty; // No recursive work
});
});
}
24. Virtualizing Time for Testing
var scheduler = new TestScheduler();
var input = scheduler.CreateHotObservable(
OnNext(300, “Bart De Smet”),
OnNext(400, “Erik Meijer”),
OnCompleted<string>(500)
);
var results = scheduler.Start(() => from name in input
select name.Length);
results.Messages.AssertEqual(
OnNext(300, 12),
OnNext(400, 11),
OnCompleted<int>(500)
);
26. Summary
• Tame your event streams using Rx and LINQ!
• Download Rx today!
– Through http://www.microsoft.com/download (search for Rx SDK)
– Using NuGet @ www.nuget.org (search for Rx-Main)
• Watch videos at http://channel9.msdn.com/tags/Rx
27. Related Content
RxJS
/* Only get the value from each key up */
var keyups = Rx.Observable.fromEvent(input, 'keyup')
.select(function (e) {
return e.target.value;
})
.where(function (text) {
return text.length > 2;
});
/* Now throttle/debounce the input for 500ms */
var throttled = keyups
.throttle(500 /* ms */);
/* Now get only distinct values, so we eliminate the arrows */
var distinct = keyups
.distinctUntilChanged();
RX++
void PrintPrimes(int n)
{
std::cout<<"Rx: first "<<n<<" primes squared"<<endl;
auto values = rxcpp::Range(2);
rxcpp::from(values)
.where(IsPrime)
.select([](int x) { return std::make_pair(x, x*x); })
.take(n)
.for_each(rxcpp::MakeTupleDispatch(
[](int p, int s)
{
cout<<p<<" =square=> "<<s<<endl;
}));
}
28. ReactiveUI
public class NewUserViewModel : ReactiveObject
{
// This is ReactiveUI's version of implementing INotifyPropertyChanged
string _Password,_PasswordConfirmation;
public string Password {
get { return _Password; }
set { this.RaiseAndSetIfChanged(x => x.Password, value); }
}
public string PasswordConfirmation {
get { return _PasswordConfirmation; }
set { this.RaiseAndSetIfChanged(x => x.PasswordConfirmation, value); }
}
ICommand OkCommand { get; protected set; }
public NewUserViewModel()
{
var canHitOk = this.WhenAny(
x => x.Password,
x => x.PasswordConfirmation,
(pass, confirm) => (pass.Value == confirm.Value && pass.Value.Length > 3));
OkCommand = new ReactiveCommand(canHitOk);
}
28
29. Resources
• Channel 9
– Curing Your Event Processing Blues with Reactive Extensions (Rx) Bart De Smet
http://msdn.microsoft.com/enus/library/windowsazure/jj860549.aspx
• IntroToRx.com
– IntroToRx.com is the online resource for getting started with
the Reactive Extensions to .Net.
• www.reactiveui.com
https://github.com/reactiveui/ReactiveUI.Samples
העולם השתנה בשנים האחרונות והאפליקציות שאנחנו מפתחים היום צריכות להיות מחוברות להמון מקורות ולקבל מידע ממידע בורסאי וכלכלי שמתעדכן בתדירות גבוהה ועד לאירועי UI וEvents סביבתיים באופן כלליהמצב קשה עוד יותר כי צריך לעשות אגרגציות על כל הנתונים ולעשות פעולות שמערבות עוד נתונים ויותר מכך, כל שירות כזה חושף API משלו שאנחנו צריכים להתאים אליוRX בא בדיוק בשביל המטרה הזו ולתת בסיס אבסטרקטי שעליו נוכל להסתכל בשביל לעבוד מול כל המקורותבסופו של דבר RX הוא Events(sobservables)+LINQ+SchedulingRX
RX בנוי בצורה שכבתית (לפחות סכמטית)בבסיס יש לנו את המודל הConcurecy וה-timeמצד אחד פעולות שאנחנו עושים צריכות להתבצע במקום מסוים , בין אם thread או tasks ואפילו על גבי הענן מצד שני יש את עניין התזמון – יש שעון של המערכת, שעון dispatcher ואפילו שעון שמגיע מהרשתRX יודע לעשות אבסטרקציה לכל זהלמעלה יש לנו את צרות העבודה מול הEVENT שקורים כאשר LINQ מאפשר לנו לעשות טיפול פלואנטי עם כל היתרונות של LINQ ולהרכיב ולעשות אגרגציה על ובין אירועים. באמצע יש את הליבה שיודעת להסתכל על אירוע
Observbable הוא מה שמייצג את האירוע והוא הגורם אליו אנחנו נרשמים כדי לקבל את הנוטיפקציה שהאירוע התרחשObservers הם הדברים שמאזינים לאירוע