Skip to content

Instantly share code, notes, and snippets.

@nantcom
Created April 25, 2021 11:42
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save nantcom/27cf92f4bc9f4c17fe08dae3bfaad5f8 to your computer and use it in GitHub Desktop.
Skeleton of Code for Creation Observable - distilled from my experience~ 😊
using System.Reactive.Linq;
public class MyStateType {
}
IObservable<MyStateType> observable = Observable.Create<MyStateType>( observer => {
// should be CancellationTokenSource
// but use bool so it easier to understand
bool stop = false;
// initialize and start the processing
// in another thread because you have to
// "Return" first to create an observable
// otherwise the thread will stuck here
// (or use theOtherClass.AnEvent += myhandler here instead
// if you are subscribing to another event)
Task.Run( ()=>{
var myStateVariable = new MyStateType();
// some long running operation
while (!stop) // or !canceller.Token.IsCancellationRequested
{
Task.Delay(1000);
observer.OnNext( myStateVariable );
}
});
// return function to call when observable was being destroyed
return ()=>
{
stop = true;
// or canceller.Cancel();
// or theOtherClass.AnEvent -= myhandler
// dispose external resource
// manage state
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment