Push new values after creation - c#

Reading IntroToRx website, it discourages using of Subject in favour of Observable.Create helper method.
As I can see, the OnNext method can be called only into subscribe method, because it's the only part I have access Observer object.
What if I would like to push new values after it's creation?
Am I "forced" to use a Subject?

If you are just exploring Rx, go for it - use Subjects, go nuts, see how they work, discover their pros and cons for yourself, then come back here and read the questions discussing why Subject is frowned upon.
Subjects offer a much easier way of "quickly bootstrapping" ideas and complicated Rx scenarios without needing to replicate the actual source conditions.
That said, they do inject state into what is kinda-sorta-supposed-to-be a stateless chain of operations, so be careful not to rely on them.
So, to sum up: if you are trying to generate sequences to test/learn how rx works or how you might make query X, use those subjects. If you find yourself using them intra-query, there is a CHANCE there is a better way.
Edit: realized I missed something:
Also, you ask if there is another way of raising stream events post-creation...the answer is yes; you might declare a stream via Create or Return or Generate that returns any old IObservable-based object that you define, which can also expose methods to inject events...or heck, have a lambda that spins a thread that checks a shared list that is routed to the return stream....I guess what I'm saying is that the possibilities are endless. There are something like a dozen "create a sequence of events" methods declared on Observable - try them all!
EDIT 2:
An example? Sure, let's throw something together using Observable.Create that mimics a really inefficient Subject:
var running = true;
var values = new ConcurrentQueue<int>();
var query = Observable.Create<int>(obs =>
{
var body = Task.Factory.StartNew(()=>
{
while(running)
{
int nextValue;
if(values.TryDequeue(out nextValue))
{
obs.OnNext(nextValue);
}
Thread.Yield();
}
});
return Disposable.Create(() =>
{
try
{
running = false;
body.Wait();
obs.OnCompleted();
}
catch(Exception ex)
{
obs.OnError(ex);
}
});
});
using(query.Subscribe(Console.WriteLine))
{
values.Enqueue(1);
values.Enqueue(2);
values.Enqueue(3);
values.Enqueue(4);
Console.ReadLine();
}
Note that this is just quick-and-extremely-dirty example code. :)

It depends on what you are trying to do. There are cases for Subjects, but just not as many as one thinks when they first start out with Rx.
How will the new data enter your sequence? Will it be from another event? Perhaps a message from a communications framework? Maybe polling a file?
Depending on these answers you will normally find that you already have some sort of event source, and you are just converting to Rx from another pattern (Events, Polling, Callbacks etc...)
You also don't just have to use Observable.Create. You could use Observable.Timer/Interval to set up a polling sequence, Observable.FromEventPattern to leverage an existing Event, Observable.Start for a one off async task style calculation etc...
As Rx (or even Linq) can be quite abstract, asking abstract questions can often lead to very broad answers. If you give an indication of a problem you are trying to solve, that might help provide you with an even better answer.

If you are receiving data from external device, you have no intention of signaling errors with IObserver.OnError (you assume your stream is endless and/or any problems with communications are within message itself), you poll at some rate, the only problem with Subject is that you will probably start polling this device even before anyone subscribes (but added benefit is that handling your state is pretty obvious, you created one object, it opened COM port, it communicates and publishes values)
Using Observable.Create or Observable.Timer/Interval might be better - but laziness is main reason, you will manage state anyway. And you will probably need to use Publish().RefCount() to prevent second subscription from opening port.

Related

Does the need to make the code simpler justify the use of wrong abstractions?

Suppose we have a CommandRunner class that runs Commands, when a Command is created it's kept in the processingQueue for proccessing, if the execution of the Command finishes with errors the Command is moved to the faultedQueue for later processing but when everything is OK the Command is moved to the archiveQueue, the archiveQueue is not going to be processed in any way
the CommandRunner is something like this
class CommandRunner
{
public CommandRunner(IQueue<Command> processingQueue,
IQueue<Command> faultedQueue,
IQueue<Command> archiveQueue)
{
this.processingQueue = processingQueue;
this.faultedQueue= faultedQueue;
this.archiveQueue= archiveQueue;
}
public void RunCommands()
{
while(processingQueue.HasItems)
{
var current = processingQueue.Dequeue();
var result = current.Run();
if(result.HasError)
curent.MoveTo(faultedQueue);
else
curent.MoveTo(archiveQueue);
...
}
}
}
The CommandeRunner recives the three dependecies as a PersistentQueue the PersistentQueue is responsible for the long term storage of the Commands and so we free the CommandRunner from handling this
And the only purpose of the archiveQueue is to keep the design homogenous, to keep the CommandRunner persistence ignorant and with few dependencies
for example we can imagine a Property like this
IEnumerable<Command> AllCommands
{
get
{
return Enumerate(archiveQueue).Union(processingQueue).Union(faultedQueue);
}
}
many portions of the class need to do so(handle the Archive as a Queue to make the code simpler as shown above)
Does it make sense to use a Queue even if it's not the best abstraction, or do I have to use another abstraction for the archive concept.
what are other alternatives to meet these requirement?
Keep in mind that code, especially running code usually gets tangled and messy as time pass. To combat this, good names, good design, and meaningful comments come into play.
If you don't going to process the archiveQueue, and it's just a storage for messages that has been successfully processed, you can always store it as a different type (list, collection, set, whatever suits your needs), and then choose one of the following two:
Keep the name archiveQueue and change the underlying type. I would leave a comment where it's defined (or injected) saying : Notice that this might not be an actual queue. Name is for consistency reasons only.
Change the name to archiveRepository or something similar, while keeping the queue type. Obviously, since it's still a queue, you'll leave a comment saying: Notice, this is actually a queue.
Another thing to keep in mind, is that if you have n people working on your code base, you'll probably get n+1 different perferences about which way it shoud be done :)
Queue is a useful structure when you need to take care about the order of items inside it. If you need in your command post process, take care about the orders commands ran, then the queue can be a good choice.
If you don't need info about the order or commands, maybe you can use a List (on System.Collections namespace).
I think your choice are good, in the same case, I'll use a queues, we have a good example with OS design principles, inside OS (on Kernel) the process are queued for execution, clearly the OS queues are more complicated because they have other variables in mind like priority, and CPU utilization, but we can learn about the use of queues like data structures in process management.

How to avoid the use of Subjects in RX

So I keep reading everywhere that use of Subject<T> is "bad" - and I kind of agree with the reasoning.
However, I am trying to think of the best way to avoid using it and have an example.
Currently I have an abstract class for my persisted configuration classes that has a protected Save() method on it which is called whenever changing a property should persist the class. This message pumps a message onto a Subject<T> which is exposed through IObservable<T> interface which the serialisation services listens to and serialises the class. This seemed the most obvious, simple and quickest way to implement this at the time.
So what would be the RX way to do this without using a Subject? Would I instead expose an event and use Observable.FromEventPattern() to subscribe to it? - as this seems a more complex way to go about it.
It's not so much that the use of Subject<T> is bad - there has to be some way of "entering the monad" - that's the academic way of saying "get an IObservable<T>". You need to start somewhere.
The problem with Subject<T> arises more when it's used from a subscription instead of chaining existing observables together. Subjects should just exist at the edges of your Rx machinery.
If none of the provided entry points (e.g. FromEvent, FromEventPattern, FromAsync, Return, ToObservable() and so on) work for you then using Subject<T> is perfectly valid. And there's no need to add extra complexity just to facilitate using one of the above - most of them use subjects or subject-like constructs under the covers anyway.
In your case, sounds like Subject<T> is just fine. You might what to look at exposing it via AsObservable() in order to hide the implementation details.
A simple way to enter the observable is via an Action
private Action<ObservableArgs> _action;
Create the observable
public IObservable<ObservableArgs> GetObservable()
{
return Observable.FromEvent<ObservableArgs>>(
ev => _action += ev,
ev => _action -= ev);
}
Then add to the observable using
public void OnNext(ObservableArgs args)
{
_action?.Invoke(args);
}

Calling commands from within another command Handle() method

Hi I am using the Simple Injector DI library and have been following some really interesting material about an architectural model designed around the command pattern:
Meanwhile... on the command side of my architecture
Meanwhile... on the query side of my architecture
The container will manage the lifetime of the UnitOfWork, and I am using commands to perform specific functions to the database.
My question is if I have a command, for example an AddNewCustomerCommand, which in turn performs another call to another service (i.e. sends a text message), from a design standpoint is this acceptable or should this be done at a higher level and if so how best to do this?
Example code is below:
public class AddNewBusinessUnitHandler
: ICommandHandler<AddBusinessUnitCommand>
{
private IUnitOfWork uow;
private ICommandHandler<OtherServiceCommand> otherHandler;
AddNewBusinessUnitHandler(IUnitOfWork uow,
ICommandHandler<OtherServiceCommand> otherHandler)
{
this.uow = uow;
this.otherHandler = otherHandler;
}
public void Handle(AddBusinessUnitCommand command)
{
var businessUnit = new BusinessUnit()
{
Name = command.BusinessUnitName,
Address = command.BusinessUnitAddress
};
var otherCommand = new OtherServiceCommand()
{
welcomePostTo = command.BusinessUnitName
};
uow.BusinessUnitRepository.Add(businessUnit);
this.otherHandler.Handle(otherCommand);
}
}
It depends on your architectural view of (business) commands, but it is quite natural to have a one to one mapping between a Use Case and a command. In that case, the presentation layer should (during a single user action, such as a button click) do nothing more than create the command and execute it. Furthermore, it should do nothing more than execute that single command, never more. Everything needed to perform that use case, should be done by that command.
That said, sending text messages, writing to the database, doing complex calculations, communicating with web services, and everything else you need to operate the business' needs should be done during the context of that command (or perhaps queued to happen later). Not before, not after, since it is that command that represents the requirements, in a presentation agnostic way.
This doesn't mean that the command handler itself should do all this. It will be quite naturally to move much logic to other services where the handler depends on. So I can imagine your handler depending on a ITextMessageSender interface, for instance.
Another discussion is if command handlers should depend on other depend command handlers. When you look at use cases, it is not unlikely that big use cases consist of multiple smaller sub use cases, so in that sense it isn't strange. Again, there will be a one to one mapping between commands and use cases.
However, note that having a deep dependency graph of nested command handlers depending on each other, can complicate navigating through the code, so take a good look at this. It might be better to inject an ITextSessageSender instead of using an ICommandHandler<SendTextMessageCommand>, for instance.
Another downside of allowing handlers to nest, is that it makes doing infrastructural stuff a bit more complex. For instance, when wrapping command handlers with a decorator that add transactional behavior, you need to make sure that the nested handlers run in the same transaction as the outer most handler. I happened to help a client of me with this today. It's not incredibly hard, but takes a little time to figure out. The same holds for things like deadlock detection, since this also runs at the boundary of the transaction.
Besides, deadlock detection is an great example to show case the power of this command/handler pattern, since almost every other architectural style will make it impossible to plug-in this behavior. Take a look at the DeadlockRetryCommandHandlerDecorator class in this article) to see an example.

Treesharp C# behavior tree library - where to start?

Recently I have been attempting to implement a robust behavior tree using the treesharp library posted by apoc. I have been going over iterators and interfaces in my books, but I still can't even figure out how to test let alone use this library. How the interfaces connect with eachother and how to actually perform a test/build a tree with them is confusing the heck out of me.
Usually in this situation, I would look for code examples and derive enlightenment from looking at other people's work, however, for this library, there does not seem to be any example code.
Could anyone help me figure out how I could start to build a behavior tree using this library? I am sorry if the question is very noobish (and I think it may be) but Enumerators and progressive interfaces within interfaces are extremely difficult for me to understand right now.
I'm the author of TreeSharp, if you guys have any questions, feel free to shoot me an email (its contained in every source file in the header).
You'll first need to understand the concepts of behavior trees (the differences between selectors, sequences, decorators, actions, and the like). I also provide a few "vanity" composites to make things slightly easier (such as Wait).
The constructor-based API lets you define trees entirely via ctors (with the use of delegates which are evaluated at runtime to provide decisions, etc)
Unfortunately I never got around to implementing the "TreeExecutor" class, which handles executing an arbitrary behavior branch from something like a Tick() method. The easiest way (using a PrioritySelector in this example, but you can use any composite) is as follows;
static void Start()
{
// Start MUST be called before you can tick the tree.
Logic.Start(null);
// do work to spool up a thread, or whatever to call Tick();
}
private static void Tick()
{
try
{
Logic.Tick(null);
// If the last status wasn't running, stop the tree, and restart it.
if (Logic.LastStatus != RunStatus.Running)
{
Logic.Stop(null);
Logic.Start(null);
}
}
catch (Exception e)
{
// Restart on any exception.
Logging.WriteException(e);
Logic.Stop(null);
Logic.Start(null);
throw;
}
}
Unfortunately, giving "examples" of its usage really depends on what you're using it for. (Since its so generic, its difficult to give examples that will make sense for any given project. I've been using it from things to AI logic, to workflows, down to scheduling processes)
A small example which may help a bit;
static Composite CreateFireMissile()
{
return new PrioritySelector(
new Decorator(ret => CurrentShip.CurrentTarget != null,
new Action(ret => CurrentShip.CurrentTarget.FireMissile())),
new Decorator(ret => CurrentShip.CurrentTarget == null,
new Decorator(ret => CurrentShip.NearbyHostiles.Count > 0,
new Sequence(
new Action(ret => CurrentShip.SetTarget(CurrentShip.NearbyHostiles[0])),
new Action(ret => CurrentShip.RotateTo(CurrentShip.CurrentTarget.Location))
)
)
)
);
}
Again, this really depends on your requirements. The library will let you subclass any composites for easier to re-use composites. (Eg; you can create a SetTargetAndRotate action, which eliminates the two actions within the Sequence)
Again, if you guys have questions, don't hesitate to ask.
Jason,
The library seems to implement all the ideas I've seen demonstrated in other examples of BT libraries. I'm looking into leveraging such a library for one of my own projects, so until I do, I'm only guessing on how to use this one based on a brief inspection.
Nevertheless, I think you would supply your own callback functions to instances of the Action class, and then piece together various actions into group combinations based on BT ideas (wait until something is true before acting, act until one of these actions is successful, perform all these actions unless one fails, etc).
HTH

C# -Priority based delegates and chaining in delegates possible? or Windows Work Flow?

Whenever i feel hungry i will publish i am hungry.This will be notified to the service providers say (MealsService,FruitService,JuiceService ).(These service providers know what to serve).
But the serving priority is the concern. Priority here means my first choice is MealsService when there are enough meal is available my need is end with MealsService.To verify the enough meal is availabe the MealsService raises the event "updateMeTheStockStatus" to the "MealsServiceStockUpdateListener" .
The "MealsServiceStockUpdateListener" will only reply back to "MealsService" . No other Service providers ( FruitService,JuiceService ) will be notified by the "MealsServiceStockUpdateListener" .If there is no sufficient stock then only the MealsService passes notification to the JuiceService (as it is the second priority).As usual it checks the stock.If stock is not sufficient it passes message to FruitService,so the flow continues like this.
How can i technically implement this?
Any implemention like priority based delagates and delegate chaining make sense ?
(Somebody! Please reframe it for good readability ).
Update : In this model there is no direct communication between "StackUpdateListener" and "me".Only The "Service Providers" will communicate me.
Like other answerers, I'm not entirely convinced that an event is the way forward, but let's go along with it for the moment.
It seems to me that the business with the MealsServiceStockUpdateListener is a red herring really - you're just trying to execute some event handlers but not others. This sort of thing crops up elsewhere when you have a "BeforeXXX" event which allows cancellation, or perhaps some sort of exception handling event.
Basically you need to get at each of your handlers separately. There are two different ways of doing that - either you can use a normal multicast delegate and call GetInvocationList() or you can change your event declaration to explicitly keep a list of handlers:
private List<EventHandler> handlers = new List<EventHandler>();
public event EventHandler MealRequired
{
add { handlers.Add(value); }
remove
{
int index = handlers.LastIndexOf(value);
if (index != -1)
{
handlers.RemoveAt(index);
}
}
}
These two approaches are not quite equivalent - if you subscribe with a delegate instance which is already a compound delegate, GetInvocationList will flatten it but the List approach won't. I'd probably go with GetInvocationList myself.
Now, the second issue is how to detect when the meal has provided. Again, there are two approaches. The first is to use the normal event handler pattern, making the EventArgs subclass in question mutable. This is the approach that HandledEventArgs takes. The second is to break the normal event pattern, and use a delegate that returns a value which can be used to indicate success or failure (and possibly other information). This is the approach that ResolveEventHandler takes. Either way, you execute the delegates in turn until one of them satistfies your requirements. Here's a short example (not using events per se, but using a compound delegate):
using System;
public class Test
{
static void Main(string[] args)
{
Func<bool> x = FirstProvider;
x += SecondProvider;
x += ThirdProvider;
Execute(x);
}
static void Execute(Func<bool> providers)
{
foreach (Func<bool> provider in providers.GetInvocationList())
{
if (provider())
{
Console.WriteLine("Done!");
return;
}
}
Console.WriteLine("No provider succeeded");
}
static bool FirstProvider()
{
Console.WriteLine("First provider returning false");
return false;
}
static bool SecondProvider()
{
Console.WriteLine("Second provider returning true");
return true;
}
static bool ThirdProvider()
{
Console.WriteLine("Third provider returning false");
return false;
}
}
Rather than publish a message "I'm hungry" to the providers, publish "I need to know current stock available". Then listen until you have enough information to make a request to the correct food service for what you need. This way the logic of what-makes-me-full is not spread amongst the food services... It seems cleaner to me.
Message passing isn't baked into .NET directly, you need to implement your own message forwarding by hand. Fortunately, the "chain of responsiblity design pattern" is designed specifically for the problem you're trying to solve, namely forwarding a message down a chain until someone can handle it.
Useful resources:
Chain of Responsibility on Wikipedia
C# implementation on DoFactory.com
I'm not sure if you really need a priority event. Anyways, let's suppose we want to code that just for fun.
The .NET Framework has no support for such a peculiar construct. Let me show one possible approach to implement it.
The first step would be to create custom store for event delegates (like described here);
Internally, the custom event store could work like a priority queue;
The specific EventArgs used would be HandledEventArgs (or a subclass of it). This would allow the event provider to stop calling handlers after one of them sets the event as Handled;
The next step is the hardest. How to say to tell the event provider what is the priority of the event handler that is being added?
Let me clarify the problem. Usually, the adding of a handler is like this:
eater.GotHungry += mealsService.Someone_GotHungry;
eater.GotHungry += juiceService.Someone_GotHungry;
eater.GotHungry += fruitService.Someone_GotHungry;
The += operator will only receive an delegate. It's not possible to pass a second priority parameter. There might be several possible solutions for this problem. One would be to define the priority in a custom attribute set at the event handler method. A scond approach is discussed in the question.
Compared to the chain of responsibility implementation at dofactory.com, this approach has some advantages. First, the handlers (your food services) do not need to know each other. Also, handlers can be added and remove at any time dynamically. Of course, you could implement a variation of a chain of responsibility that has this advantages too.
I don't think delegates are the proper solution to your problem. Delegates are a low-level service provided by C# for relatively tightly coupled events between components. If I understand your question properly (It is worded a little oddly, so I am not sure I clearly understand your problem), then I think what you need is a mediated consumer/provider.
Rather than having your consumers directly consume the meal, juice, and fruit providers, have them request a food item from a central mediator. The mediator would then be responsible for determining what is available and what should be provided to the consumer. The mediator would be a subscriber to events published by all three services. Whenever stock is added/updated in the Meal, Juice, or Fruit services, they would publish their current stock to all subscribers. The mediator, being a subscriber, would track current stock reductions on its own, and be able to determine for itself whether to send a meal, juice, or fruit to a food consumer when a get food request is made.
For example:
|---------- (GetFoodResponse) ----------------
V |
FoodConsumer ---- (GetFoodRequest) ------> FoodProvider <-----> [ Local Stock Data ]
^
|
|
MealService ---- (PublishStockMessage) ----------|
^
JuiceService --- (PublishStockMessage) ----------|
^
FruitService --- (PublishStockMessage) ----------|
The benefits of such a solution are that you reduce coupling, properly segregate responsibility, and solve your problem. For one, your consumers only need to consume a single service...the FoodProvider. The FoodProvider subscribes to publications from the other three services, and is responsible for determining what food to provide to a consumer. The three food services are not responsible for anything related to the hunger of your food consumers, they are only responsible for providing food and tracking the stock of the food they provide. You also gain the ability to distribute the various components. Your consumers, the food provider, and each of the three food services can all be hosted on different physical machines if required.
However, to achieve the above benefits, your solution becomes more complex. You have more parts, and they need to be connected to each other properly. You have to publish and subscribe to messages, which requires some kind of supporting infrastructure (WCF, MSMQ, some third party ESB, custom solution, etc.) You also have duplication of data, since the food provider tracks stock on its own in addition to each of the food services, which could lead to discontinuity in available stock. This can be mitigated if you manage stock updated properly, but that would also increase complexity.
If you can handle the additional complexity, ultimately, a solution like this would more flexible and adaptable than a more tightly connected solution that uses components and C# events in a local-deployment-only scenario (as in your original example.)
I am having a bit of trouble understanding your analogy here, which sounds like you're obscuring the actual intent of the software, but I think I have done something like what you are describing.
In my case the software was telemarketing software and each of the telemarketers had a calling queue. When that queue raises the event signifying that it is nearing empty, the program will grab a list of available people to call, and then pass them through a chain of responsibility which pushes the available call into the telemarketer's queue like so:
Each element in the chain acts as a priority filter: the first link in the chain will grab all of the people who have never been called before, and if it finishes (ie. went through all of the people who have never been called) without filling up the queue, it will pass the remaining list of people to call to the next link in the chain - which will apply another filter/search. This continues until the last link in the chain which just fires off an e-mail to an administrator indicating that there are no available people to be called and a human needs to intervene quickly before the telemarketers have no work to do.

Categories

Resources