RxJS and WebWorkers - angularjs

Quick question
If I have a WebWorker that has a function that returns an Observable<Any> back to the UI code, if I then subscribe to the Observable, is the observable running on the UI thread or the WebWorker thread?
I ask this question because I am writing an Angular2 app with RxJS, and to improve performance I want some of the hard-working Observables to run within WebWorkers, passing a stream of results over to the UI thread

I assume your web worker is sending an observable back to your main thread via a message.
Messages are intended to be used both ways, you can't send objects that expose functionality.
The solution is to have your webworker post messages, and then have a main-thread service handle those messages and pipe them into a Subject, which it exposes to your application as an IObservable.
Keep on mind that web worker messaging doesn't support channels, so you'll need to apply your own discriminator if you use messages on multiple areas of your app.

The short answer is that Rx doesn't introduce concurrency unless you instruct it to via SubscribeOn, ObserveOn or some transform operator like Buffer.
So any code in the "Subscribe" part of the Rx operator will run in the same thread you called .Subscribe(onNext etc). However the actual callbacks onNext, onError and onComplete will run on whatever thread the observer uses, you don't control this (unless you wrote the operator).
To ensure you receive calls on the UI thread you should add a .ObserveOn(UIDispatcherThread). This will guarantee the thread you are called back on and make it testable.
Hope that helps.

As others noted, communication between calling code and webworkers is serialized and so you cant send something that has behavior (such an observable) over the wire.
I've written a little helper that uses Rxjs to help resolve this and other pains of developing with webworkers. Read about it here, github repo here

Related

Angular 2 architecture for server-side communication

Learning Angular 2. What would a recommended file structure for having components communicating with a server?
So a feature, say a todo feature. It may have a main todo-component, a todo-list-component, a todo-item-component, new-todo-component and a todo-service (and probably more).
Then there is another feature, say a personal activity timeline, which takes several source (including new and finished todos) and present it to the user. Say it may have the same type of files, but so different that we could not combine them into generic ones: a main timeline-component, a timeline-list-component, a timeline-item-component and a timeline-service.
Then we want for both the todo and the timeline features to communicate with the server. Since they both access partly the same data, perhaps a good idea would to have a backend-service to take care of the server communication for both features.
But how should the components get the data it's need? Should the todo components ask the todo-service which in turn asks the backend-service (and similar for the timeline components)? Or should the components better use the backend-service directly, so for example the todo components would use backend-service for backend stuff and todo-service and for other things that is naturally to put in a service? Since this is async and there are observables involved (which in the first case would need to be sent over multiple "steps" somehow), perhaps the latter is a simpler/cleaner approach?
Ideally the Component should use a proper Service to pipe itself into the data flow with Observables.
If we look for instance at the Chat application example we can see that each Service has a clear responsibility for the data management.
I wouldn't allow a Component to access a generic Http service as it would need to host too much logic to communicate with the server: the component doesn't care about the data source, just shows the data.

ExtJs component cleanup

I read the following comment in ExtJs-in-action -
'Do not dismiss the destruction portion of a Component’s lifecycle if you plan on developing your own custom
Components. Many developers have gotten into trouble when they’ve ignored this crucial step and have code that
has left artifacts such as data Stores that continuously poll web servers...'
I have never called explicit destructors/destroy on my my containers/components in 3.4.x
Though things seem to work fine - I am curious on
1. What are some instances where implementing destructors becomes essential
2.what is the proper convention to handle component destruction on close of browser instance.
This guide may be a good read.
You should always consider cleaning up your objects after they are needed to free up memory, especially unbinding event listeners and any timers you've created with setInterval. Once the object reference is destroyed you cannot access it but it could still be listening to or firing events and using up resources.
Generally in ExtJs, You free up resources in the destroy method, but just remember to call the callParent() function too so that ExtJs does it's own cleanup.
Here is another article from IBM in 2012 that seems to go into more depth on the subject.

Specific working example needed using IProgress interface described by Albahari

I am a neophyte at C# threading. I am trying to get my head around how to make 100K web requests, with some degree of parallelism, and report progress real-time to the GUI:
urls processed so far: ######
total moved so far: ######
timed out so far: ####3
I am reading pages 596ff in C# 5.0 in a Nutshell by the Albahari brothers, the section on Progress Reporting. At this point, I don't see how in the Progress instance these counters would be incremented in a thread-safe manner, and exactly how/where the UI gets updated. EVen in the example specifically discussing the differences between writing to the console and writing to the GUI, the book uses Console.WriteLine. I'd be grateful for an example showing exactly what occurs in the Progress instance -- incrementing some int variables and writing to a textbox, for example.
I have a walkthrough on my blog, in particular pointing out the caveats:
IProgress<T>.Report is asynchronous, so it works best if the object you send it is immutable.
By convention, the IProgress<T> progress passed into your TAP method may be null, so check for that before reporting progress.
Progress<T> works best with a UI or other single-threaded SynchronizationContext.
Exceptions raised from Progress<T>'s handler go directly to the SynchronizationContext, so avoid throwing exceptions from the progress report handler.
There's also a blog post here and the MSDN docs are quite good.

Consuming a per session WCF service in a WPF application

I'm not really sure how to handle the scenario I have in a good code manner.
The basic of the criteria of my work is this:
A WPF application that consumes a WCF service
The service uses per session instancing
The session starts soon after application is started and should live through the application lifetime (with small exceptions)
Some method calls in a session must precede and be finished before others are called
This means I will have to be able to have one instance of a proxy client throughout the whole application. I will also have to be able to handle async calls, so the client won't hang up, but at the same time ensure they are finished.
My technical understanding go WCF is limiting enough to not know if certain scenarios would work as intended. So I'm going to list my uncertainties:
When does a session start and when does it end. Is it based on the creation of clients or could a separate client instance access the same session if the first would go faulted.
What is the best way to handle exceptions through a WCF service
Is ChannelFactory something I should look at to help me put here.
So what I did in the first iteration to try to solve some of these problems.
I used dependency injection to inject the client instance throughout the classes of my WPF application (I'm using MVVM) to ensure the same instance is everywhere.
I made the service reference using the asynchronous generation method to get the Begin and End versions of all methods to ensure the calls would be async
I used the Coroutine (IResult interface) feature of the Caliburn.Micro framework to ensure one async action is finished before the other begins (have no idea if this is a proper usage or if it is a smart move at all).
Problems I still have is of course how to handle a faulted state of the client. I'm assuming right now that I could reinstance the client and either rescue the session or I could actually just set it up again as it was. I now need to reinstance it everyplace I injected it in with the same new instance.
So I though perhaps it would be best to create a ClientManager class that would wrap the Client. That way I could inject this ClientManager and reinstance inside of him if needed. I guess I should expose him outwards to be able to make method calls but it would be great if I could error handle inside him in somehow. I'm just having a hard time testing my methods and I'm never certain it will work properly in integration because I don't understand all of the inner workings of WCF, coroutines and threading.
Is there anyone out there with more experience then me in these matters that could give me a few pointers or at least tell me how WCF works in these situations ( per session ) and what I'm doing wrong and what right.
WCF supports sessions out-of-box, so I would recommend starting with this MSDN article.
At a very high level, first you set SessionMode=SessionMode.Required in your ServiceContract. And then, set the IsInitiating=True and IsTerminating=True properties on your OperationContract's to mark the start and end of each session.
However, note that WCF limits concurrent sessions by default to 16 to prevent DOS attacks, but you can always up the value. Also, you would have realized that the session is valid as long as its host (IIS / Windows Service / other) is not recycled.
On a related note, I have used WCF Durable Services earlier - which are meant to persist the state of your WCF service in a data-store (default is SQL Server). Ofcourse, there is a performance hit here. Suggest reading further to see if this is the right choice for you.
Hope this helps.

Handling multiple threads that need UI access

We have an application that is essentially implementing its own messaging queue. When a user interacts with the application it will generate an action, being a custom action and not the .NET class, that will be handled by our ActionDispatcher.
In the ActionDispatcher class I have a Stack of CustomAction objects. I'd like to run the ActionDispatcher in its own thread, but then you have all the issues with communicating with the main UI thread using Invoke and BeginInvoke.
There are several different methods that the ActionDispatcher may call, each one would require a delegate on the UI side to be used to communicate with the other thread I believe. Is there a simplier way?
The reason for wanting a seperate thread is that the ActionDispatcher processes messages that originate from a server as well as the UI. This is a client application, and many actions are generated by the server. The idea is that I have we have our own queue that both the UI and server add messages to.
It really depends on the architecture of your application, but the quick and short answer is: No. If you're not on the UI thread, then you have to use the Dispather's Invoke or BeginInvoke method to get access or execute code back on the UI thread.
As a side note, this is a little different than in WinForms, it almost sounds like you're coming from a WinForms perspective, so you might want to look up the WPF Dispatcher.
On the other hand, I would suggest that you look into something like Prism's IEventAggregator. I'm sure there are other similar implementations, but Prism has one nice feature, you can tell it you want to subscribe to an event and have it come in on the UI thread and prism does the rest of the work for you.
Personally, I think using an EventAggregator pattern is better, I'm not sure it's necessarily simpler though.
You need to use Dispatcher.CheckAccess().
http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.checkaccess.aspx

Resources