What is RxJS's place in the JS ecosystem and evolution? - javascript

To be clear, I'm hoping for factual information to be presented about RxJS and how it relates to JavaScript's evolution, not a matter of opinion on how good RxJS is, etc.
My question is: is RxJS ( https://github.com/Reactive-Extensions/RxJS ) somewhat of a forward-looking polyfill because of Object.observe, etc. not being standard among browsers yet, or does it fundamentally offer things beyond the scope of what native JS offers and beyond what JS standards seek to offer in the foreseeable future? (Granted, perhaps someday native JS may be capable of X, Y, Z that aren't currently on the radar; I'm not interested in guesses on those.) Perhaps it's a combo.
My motivation/interest in the question is in considering the investment of learning and implementing RxJS in applications, weighed against the timeline of native JS solutions being available, and/or whether there are other considerations to be mentioned that I have not touched on here.

RxJS was birthed as a JavaScript port of Rx.NET. It is not a forward looking polyfill of Object.observe.
RxJs is a library for working with asynchronous operations, with special emphasis on multi-valued operations. The library gives the developer a common "language" they can use to write functional code to manipulate asynchronous streams no matter the stream source. The same "language" works with any combination of UI events, timer events, object mutation observations, animation frames, ajax calls, websocket messages, webworker messages, promises, etc
Object.observe is a mechanism to observe changes in an object. RxJS does not provide this functionality. But RxJS complements this functionality: As an object is changed over time, it can be thought of as a source of asynchronous object change notifications. It is fairly straight-forward to convert these observations into an RxJS source, (e.g. something like Rx.Observable.observeObject(someObject)), which would then let you work with object changes as just another asynchronous RxJs stream with all of the vast array of tools RxJS makes available to you.

RxJs is the library which helps us to do Reactive Programming.
Reactive Programming is a pattern of development that works with asynchronous data stream created of UI Events, HTTP Requests, File System, cache etc. So data stream is an ongoing event sequence in time orderly manner. The stream can emit value, error, and status signal.
Observables are to watch these streams and trigger function on anything occurs in the stream. Observers can subscribe to observables.
Ref- http://technobelities.blogspot.in/2017/02/rxjs-quick-start.html
As per MSDN -
Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Reactive Extensions represents all these data sequences as observable sequences. An application can subscribe to these observable sequences to receive asynchronous notifications as new data arrive.

Related

What are the advantages of a rxjs Observable over a DOM event?

I have been studying rxjs and reactive programming but there is something I didn't quite understand yet.
For instance, I want to get the result of a keyup event on a simple input, map it, and set the map result as another div content:
const root = $('#root'),
input = root.find('#some-input'),
result = root.find('#result');
Using rxjs, I can do:
const keyupObs = fromEvent(input, 'keyup');
const mapper = keyupObs.pipe(
map(e => $(e.target)),
tap(t => result.html(t.val()))
).subscribe(t => console.log(t));
Using a jquery driven event, I can write:
input.on('keyup', e => result.html($(e.currentTarget).val()));
Which is less code and for a begginer like me does not seem to differ that much from what I wrote using rxjs.
So what are the main advantages of using rxjs, and why should I use it over DOM driven events(in this case using jQuery)?
Take the definition of observable:
Observables are lazy Push collections of multiple values.
This in itself, does not mean much. In your case, the event mechanism suits your needs and simulates the stream.
What if you wanted to:
Merge values with another stream?
Map and modify in a complicated way the output?
Have asynchronous streams that promises don't support?
Cache the output after the first value?
Use it across components and services?
Event observable provides the least value on its own but if you want to consume and combine with others, the observable will provide a plethora of operators to play with.
the main benefit here is that you can use rxjs operators if you expose the DOM event as an observable, ie filtering or switching or combining or debouncing is easier.
you have finer control over when to start and stop listening via subscribe and unsubscribe. You also have an easier time preventing memory leaks so long as you unsubscribe properly.
a layer of abstraction over the DOM is helpful for a number of reasons. such as, if the context of your app ever changes, your app is more portable, or if the DOM interface ever changes, rx should be doing their best to keep you insulated from it. you're also better insulated from cross browser issues. Though in theory jquery should be handling this as well, but in my experience jquery is operating under the assumption that you’re in a browser like environment whereas rxjs is less so.

Javascript implementation of Event Aggregator pattern

So I have done a lot of research and for some reason I can't find an implementation of the Event Aggregator pattern in Javascript. In fact, the only language that's always used is C# and there's always generics being used. It's a very useful pattern so I fail to realize why it only seems to be 'meant' for .NET. I was hoping that someone would be able to provide an implementation in Javascript or at the very least Java and NOT C# (I've seen enough of that). Thank you!
How to:
Get one on the many general purpose publish/subscribe libraries that are implemented and ready to use. ie https://github.com/mroderick/PubSubJS (or roll your own - it ain't that hard)
Instantiate your event source objects, implement publishing of events.
Instantiate your aggregator, make it subscribe to your source objects, and offer publishing of received events.
Instantiate your target objects, make them subscribe to your aggregator.
In Javascript the Event Aggregator pattern does not need its own implementation. It is just an object that subscribes to multiple publishers and also publishes to multiple subscribers.
Since there are no type checking or interfaces anything of that sort, you dont need the pattern implemented before you use it, it is just a trivial exercise in pub/sub, which is probably why you can't find it anywhere as an "abstract" implementation.
Look into redux if you want to see something reusable that solves problems in the same domain as the event aggregator pattern, but offers a lot more.

What is the difference between making several simple subscriptions and a single complex one?

Is there any practical difference between keeping several simple (plain) subscriptions and keeping a single complex (many levels) one? (with publish-composite, for example)
Seems to me that there shouldn't be any difference, but I wanted to be sure. I prefer sticking to plain subs as it seems to make the code clearer in highly modular projects, but only if that wouldn't bring any performance or scalability issues.
So, can someone help me?
There are two key differences in doing several plain subscriptions vs. keeping complex composite subscription
1) Exposure/Privacy
A composite subscription allows you to perform joins/filters on the server side to ensure that you only send data that the current user has authority to see. You don't want to expose your entire database to the client. Keep in mind that even if your UI is not showing the data, the user can go into the console and grab all the data that your server publishes.
2) Client performance
Performing joins/filters on the client can be expensive if you have a large dataset. This is of course dependent on your application. Additionally, if the database is constantly being updated, and those updates should not be visible to the user; you will constantly need to transfer the updates to the client without deriving benefits from the network expense.
I think this question can't be given a precise answer without more details specific to your application. That being said, I think it's an important question so I'll outline of some things to consider.
To be clear, the focus of this answer will be debating the relative merits of server-side and client-side reactive joins.
decide if you need reactivity
You can produce a simple join of multiple collections without any reactivity in the publisher (see the first example from the article above). Depending on the nature of the problem, it may be that you don't really need a reactive join. Imagine you are joining comments and authors, but your app always has all of the possible authors published already. In that case the fundamental flaw in non-reactive joins (missing child documents after a new parent) won't exist, so a reactive publication is redundant.
consider your security model
As I mention in my article on template joins, server-side joins have the advantage of bundling all of your data together, whereas client-joins require more granular publishers. Consider the security implications of having a publisher like commentsAndAuthors vs two generic implementations of comments and users. The latter suggests that anyone could request an array of user documents without context.
server joins can be CPU and memory hogs
Look carefully at the implementation of the library you are considering for your server-side joins. Some of them use observe which requires that each complete document in the dependency chain be kept in memory. Others are implemented only on observeChanges which is more efficient but makes packages a bit less flexible in what they can do.
look for observer reuse
One of your goals should be to reuse your observers. In other words, given that you will have S concurrent subscriptions you will only end up doing ~(S-I) work where I is the number of identical observers across clients. Depending on the nature of your subscriptions, you may see greater observer reuse with more granular subscriptions, but this is very application specific.
beware of latency
A big advantage of server-side joins is that they deliver all of the documents effectively at once. Compare that to a client join which must wait for each set of parent documents to arrive before activating the child subscriptions. A N-level client-join would have N round-trips before the initial set of documents will be delivered to the client.
conclusion
You'll need to take all of the above into consideration when deciding which technique to use for each of your publications. The reality is that benchmarking a live app on something like kadira is the only way to arrive at a conclusive answer.

What is the difference between Object.observe and Object.watch

Object.watch: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch
Object.observe: http://wiki.ecmascript.org/doku.php?id=harmony:observe
They both seem do the same thing at a high level. What are the salient differences between them?
There are many difference.
Microtasks vs synchronous callbacks
One difference is that Object.observe makes callbacks when you enter the message loop. I.e. many changes to the object results in a single callback with all changes rather than multiple callbacks.
When listening to changes on the DOM, the mutation events was replaced with mutation observers for the same reason. The microtask solution is simply more performant than the synchronous callback.
Standard vs non-standard
In addition, Object.observe is a suggested Ecmascript standard for Ecmascript 7. I.e. it is a proposed Javascript standard.
Intent
Object.observe is intended as a performant way to monitor changes to an entire object and the use case is expected to entail listening to many objects. This is a requirement for binding frameworks (i.e. client side templating) such as AngularJs and Polymer. Object.watch is more a Firefox feature to monitor a specific property and is sprung out of a debugger feature.

javascript promises and futures similar to C++

are there any javascript libraries which provide promises and futures syntactically similar to that of C++ ones. basically we want to use them in webworkers, I dont want a callback interface. I want the webworker to block on a future and continue when the UI thread sets the value of the future. i have looked at every possible promise and future library but every thing expects a callback, our code is already a mess and we dont want to further complicate it.
http://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/ses-promise.js
Implementation of promises for SES/ES5. Exports Q to the global scope.
Mostly taken from the ref_send implementation by Tyler Close, with the addition of a trademark table to support promises for functions.
Btw, Mark Miller is working on codifying JavaScript's concurrency model and adding eventual send semantics with syntactic sugar for a future version of the language. From http://wiki.ecmascript.org/doku.php?id=strawman:concurrency
Reality: Codifying and formalizing JavaScript’s de-facto concurrency model as a de-jure model.
Promises: A way to (Q(p).post(), Q(p).get()) Make asynchronous requests of objects that may not be synchronously reachable, such as remote objects. (Q(p).when()) Ease the burden of local event loop programming, by reifying the ability to register a callback as a first class value. (Q.async, yield:) for implicit registration of shallow continuations on promises.
Syntactic sugar. The infix “!” operator: An eventual analog of “.“, for making eventual requests look more like immediate requests.
(Q.makePromise()) A promise extension mechanism, so that promise handlers can turn local promise operations into remote messages.
Transport independence: Using remote object messaging as a symmetric abstraction layer, hiding the annoying differences among the various transports listed above as well as server-to-server TCP and UDP transports.
(Vat()) An event-loop spawning mechanism for spawning new event loops that run concurrently with the event loop which spawned it.
Worker independence: Using Vat API as an abstraction layer around worker spawning on the browser or process spawning on the server.
(Vat.evalLater(), where()) Using JavaScript itself as mobile code, so event loops can safely inject new behavior into other event loops
Symmetric Mobile Code: Generalizes from the current use of JavaScript as mobile code sent only from server and only to browsers.
Async-PGAS: Provides a distributed analog to the expressiveness of The Asynchronous Partitioned Global Address Space Model.

Categories

Resources