How to observe UI events with the correct Scheduler with RxJava? - reactive-programming

Say I have a generic 'Button' in any kind of modern UI framework (I'm working with Android's right now but the problem is pretty much plaform-agnostic). I can put a listener onto this button to listen for click events. My listener gets notified about click events on the UI-thread. This is a problem from a reactive-point-of-view, more specifically in the context of threading.
I can easily create a Subject for the click events. The Observer would most likely want to do processing on another thread. But I can't easily extract (without hacking or ugly workarounds) the Scheduler's Worker from an .observeOn() operator, for dispatching the event onto the correct Worker.
How do I create an Observable stream from these click events, so that the stream will respect the Scheduling requirements of the .observeOn() operator?

It's not clear to me what exactly the issue is here. ObserveOn puts the events to the specified scheduler, which behind the scenes may end up on different threads for different subscribers. If you want to make sure every subscriber will receive the events exactly on the same thread, you need to have a Scheduler with exactly one backing thread. The easiest way of getting such Scheduler is by wrapping an ExecutorService:
Scheduler s = Schedulers.from(Executors.newSingleThreadedExecutor());
PublishSubject<Event> ps = PublishSubject.create();
Observable<Event> events = ps.observeOn(s);
events.subscribe(...);
events.subscribe(...);
ps.onNext(...);

Related

Is it possible to get a response from event fired through Akka Event Stream (scala)?

In are app, we are quite heavily using Akka Event Stream to handle logic that is not related to the main business flow. Things like: send emails, sync records, etc... All of these events are currently fired and forgotten.
system.eventStream.publish(<event>)
And they are handled by listeners, asynchronously, in most cases.
However, I am now investigating an option of extending class functionality through events system and that, sometimes, requires a return value from an event?
Is it even possible to get some result back from an event? I could not find anything specific in this regard.
Thanks,
It's a feature of event based systems: you know who triggered the event, you don't know who will handle it, nor when (can be asynchronous).
So, the most idiomatic solution, if your listener should generate an answer, is to do it in an asynchronous way. And as such, the listener should send an event with it's answer.
Another way to do it is to bypass the event bus and register you handlers as listeners of your event source (you should handle your self the registe/unregister functions through akka messages and a simple list). And when your event source triggers the listeners, it can do it using the ask pattern.

Flux - How to deal with multiple stores updating the same view?

I'm a beginner to the flux model but I think I understand it at a high level:
event creator -> events -> dispatch -> store -> view and around we go!
Given that the flux model supports multiple stores, if you have say an event loop that dispatches to 2+ stores, that in turn updates the same view.
How do you manage any inadvertent flicker that would come from that process?
I haven't quite enabled/used react yet (I assume a catch all answer will be that react handles this heavy lifting part of reducing this) but conceptually how could this work outside a specific implementation.
Since store changes are applied serially across stores, do you just wait until all the stores are down processing the dispatcher, and then allow them individually to fire all their changes? Even then you still would loop through and dispatch events at the end, and you'd still potentially have overlapping updates to the UI.
Thanks!
You have different options here:
The vanilla solution is to utilize a waitFor() function in your store-structure, and ensure that in the end each component has only one store it listens to. More or less like this:
Caveat is that your action types and store structures need to be in sync: Each action needs to communicate to all stores that are included in a waitFor cycle. The example in the picture will fail to trigger a render. The top-most store is not listening to the action from dispatcher, and the right store will keep waiting for update. Also, the red line may cause a similar dead end, if it is only 1 of the components. My way of dealing with this is: make all stores in the first line listen to ALL actions, and if the action is irrelevant: emit change.
The other option is to consolidate your data into a single store.
This does not make the issue go away: you need to handle the dependency issues inside the single store. But it does take away the hassle of many actions, many waitFors, and many change emissions..
Remember that the action is processed synchronously - all stores will have emitted, the controller views with have called setState, etc. before the stack unwinds and browser gets a chance to re-render the DOM, so flicker is not possible (the browser won't render in the middle of a function running, since otherwise all DOM manipulation code would cause random flickering).
However, as you say, there will potentially be multiple stores emitting changes, and multiple components listen to them, and hence you may end up calling 'setState' multiple times (even on the same component). This sounds inefficient, but under most circumstances it isn't. As long as the current action originated from an event that came from React (e.g. an event handler added to a component in the JSX), React automatically batches all calls to setState and only does the re-render to the DOM (i.e. any required DOM updates) once, immediately (and synchronously) after you have finished processing the event.
There is a case to be aware of - if you dispatch an action from something outside of a React event handler (e.g. a promise.then, an AJAX callback, setTimeout callback, etc.) then React will have to re-render for every single call to setState in that function, since it doesn't know when else to do it. You can avoid this by using the undocumented batched rendering feature (0.14, note that 0.13 had a different API for this):
ReactDOM.unstable_batchedUpdates(myFunctionThatDispatchesActions);
An alternative might be to use an off-the-shelf Flux implementation which does this for you already. See e.g. https://github.com/acdlite/redux-batched-updates

Using Commands, Events or Services

When designing an application's back-end you will often need to abstract the systems that do things from the systems that actually do them.
There are elements of this in the CQRS and PubSub design patterns.
By way of example:
A new user submits a registration form
Your application receives that data and pushes out a message saying “hey i have some new user data, please do something with this”
A listener / handler / service grabs the data and processes it
(please let me know if that makes no sense)
In my applications I would usually:
Fire a new Event that a Listener is set up to process Event::fire('user.new', $data)
Create a new Command with the data, which is bound to a CommandHandler new NewUserCommand($data)
Call a method in a Service and pass in the data UserService::newUser($data)
While these are nearly exactly the same, I am just wondering - how do you go about deciding which one to use when you are creating the architecture of your applications?
Fire a new Event that a Listener is set up to process
Event::fire('user.new', $data)
Event pattern implies that there could be many handlers, subscribing to the same event and those handlers are disconnected form the sender. Also event handlers usually do not return information to the sender (because there can be actually many handlers and there is a confusion about whose information to return).
So, this is not your case.
Create a new Command with the data, which is bound to a CommandHandler
new NewUserCommand($data)
Commands are an extended way to perform some operation. They can be dispatched, pipelined, queued etc. If you don't need all that capabilities, why to complicate things?
Call a method in a Service and pass in the data
UserService::newUser($data)
Well, this is the most suitable thing for your case, isn't it?
While these are nearly exactly the same, I
am just wondering - how do you go about deciding which one to use when
you are creating the architecture of your applications?
Easy. From many solutions choose only those, which:
metaphorically suitable (do not use events, where your logic does not look like an event)
the simplest (do not go too deep into the depths of programming theories and methods. Always choose solution, that lowers your project development complexity)
When to use command over event?
Command: when I have some single isolated action with few dependencies which must be called from different application parts. The closest analogue is some editor command, which is accessible both from toolbar and menu.
Event: when I have several (at least in perspective) dependent actions, which may be called before/after some other action is executed. For example, if you have a number of services, you can use events to perform cache invalidation for them. Service, that changes a particular object emits "IChangedObject" event. Other services subscribe to such events and respond to them invalidating their cache.

CQRS - can EventListener invoke Command?

I want to use elements of CQRS pattern in my project. I wonder if i do it right with Command and Events.
The thing that I'm not sure is if event can invoke command. To better show what i want to do I will use diagram and example.
This is an example:
User invoke TripCreateCommand. TripCreateCommandHandler do his job and after success publish TripCreatedEvent.
Now we have two listener to TripCreatedEvent (the order of listener execution does not matter)
First listener (can be execute after the second listener):
for each user in trip.author.friends invoke two Command (the order of commands is important)
PublishTripOnUserWallCommand
SendNewTripEmailNotificationCommand
SendNewTripPlatformNotification
Second listener (can be execute before the first listener):
PublishTripOnUserSocials
And this is sample diagram:
Is this a good way ? Can EventListener invoke Command, or maybe I should do it in some other way ?
Your question is about Mesage Driven Architecture which works together with but otherwise unrelated to CQRS.
Anyway, your diagram is almost correct. The event subscriber/handler (I prefer this terminology) can send new Commands via the service bus, but it's not a rule that you should always do this. I implement quite a lot of functionality directly in the event handler, although probalby would be more clean and reliable to send a new command. It really depends on what I want to do.
Note that the message handlers (commands or events) should not know about other handlers. They should know about the bus and the bus takes care of handling. This means that in your app, the event handlers would take the bus as dependency, create the command and send it via the bus. The event handler itself doesn't know what command handler generated the event and can 'reply' to it.
Usually the commands would be handled independently and you can't guarantee the order (unless they're handled synchronously) so maybe you want the second command to be issued as a result of the first command's handling. Indeed, it can be the case for a Saga.
AFAIK you are talking only about doing things synchronously, so your approach works in this case but it's probably not scalable. Moving to async handling will break this execution flow. However your application can be fine with it, not everyhting needs to be twitter.
A message driven architecture is not that straightforward and for some cases (like you want an immediate response from the backend) it's quite complicated to implement, at least more complicated than with the 'standard' approach. So maybe for those particular cases you might want to do it the 'old' way.
If you're worried about decoupling and testing, you can still design the services as they were message handlers but use them directly, instead of a service bus.
Not sure why you would need Commands for performing the updating the information on the user's wall. Why would you choose not to use a View Model Updater for that task.
Sending an email can be considered a Command but could also easily be viewed as just another View Model update.
Not clear on what the purpose of the SendNewTripPlatformNotification is, so I cannot give any suggestions there...
Some of this could also be a candidate for a Saga. Secondly I'm missing your Domain in the diagram, that is what should be responsible for publishing any events, or do you consider the CommandHandler to be the Domain?

Application.DoEvents, when it's necessary and when it's not?

What is the necessity of using Application.DoEvents and when we should use it?
Application.DoEvents is usually used to make sure that events get handled periodicaly when you're performing some long-running operation on the UI thread.
A better solution is just not to do that. Perform long-running operations on separate threads, marshalling to the UI thread (either using Control.BeginInvoke/Invoke or with BackgroundWorker) when you need to update the UI.
Application.DoEvents introduces the possibility of re-entrancy, which can lead to very hard-to-understand bugs.
Windows maintains a queue to hold various events like click, resize, close, etc. While a control is responding to an event, all other events are held back in the queue. So if your application is taking unduly long to process a button-click, rest of the application would appear to freeze. Consequently it is possible that your application appears unresponsive while it is doing some heavy processing in response to an event. While you should ideally do heavy processing in an asynchronous manner to ensure that the UI doesn’t freeze, a quick and easy solution is to just call Application.DoEvents() periodically to allow pending events to be sent to your application.
For good windows application, end user doesn’t like when any form of application are freezing out while performing larger/heavyweight operation. User always wants application run smoothly and in responsive manner rather than freezing UI. But after googling i found that Application.DoEvents() is not a good practice to use in application more frequently so instead this events it’s better to use BackGround Worker Thread for performing long running task without freezing windows.
You can get better idea if you practically look it. Just copy following code and check application with and without putting Application.DoEvents().
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To 1000
System.Threading.Thread.Sleep(100)
ListBox1.Items.Add(i.ToString())
Application.DoEvents()
Next
End Sub
Imho you should more less never use it, as you might end up with very unexpected behavior.
Just generated code is ok. Things like you are executing again the event handler you are currently in,because the user pressed a key twice etc etc.
If you want to refresh a control to display the current process you should explicitly call .Update on that control in instead of calling Application.DoEvents.