What is the difference between future and promise in vertx? - promise

I usually see the use of either promise and future in the start of a vert.x verticle. Is there any specific difference between both?
I have read about their differences in Scala language, is it the same in case of Vert.x too?
Also when should I know when to use promise or a future?

The best I've read about:
think on Promise as producer (used by producer on one side of async operation) and Future as consumer (used by consumer on the other side).
Futures vs. Promises

Promise are for defining non-blocking operations, and it's future() method returns the Future associated with a promise, to get notified of the promise completion and retrieve its value. The Future interface is the result of an action that may, or may not, have occurred yet.

A bit late to the game, and the other answers say as much in different words, however this might help. Lets say you were wrapping some older API (e.g. callback based) to use Futures, then you might do something like this :
Future<String> getStringFromLegacyCallbackAPI() {
Promise<String> promise = Promise.promise();
legacyApi.getString(promise::complete);
return promise.future();
}
Note that the person who calls this method gets a Future so they can only specify what should happen in the event of successful completion or failure (they cannot trigger completion or failure). So, I think you should not pass the promise up the stack - rather the Future should be handed back and the Promise should be kept under the control of the code which can resolve or reject it.

A Promise as well is a writable side of an action that may or not have occurred yet.
And according to the wiki :
Given the new Promise / Future APIs the start(Future<Void>) and stop(Future<Void>) methods have been deprecated and will be removed in Vert.x 4.
Please migrate to the start(Promise) and stop(Promise) variants.

As a paraphrase,
A future is a read-only container for a result that does not yet exist, while a promise can be written (normally only once).
More from here

Related

GraphQL resolvers - when to make resolver functions async or not?

I completed this tutorial on making a graphql-node backend server built on Prisma2 and GraphQL. The tutorial doesn't explain why it writes some Resolver functions async and some not.
I thought that the async was added to functions that interacted with the database, but you can see this resolver gets data from the database but doesn't use async. But in this resolver it does use async.
Can somebody please explain why there is this seemingly arbitrary usage of async? When and why I should use it? Thanks in advance.
The first thing you should do is read up on Promises. Promises are a way in JavaScript to encapsulate computations that are still ongoing. This is usually the case when you talk to an external service like a database or the operating system. They have been replacing callback style APIs.
In GraphQL a resolver can either return a value or a Promise that resolves to a value. This means, you can freely choose returning a value or a Promise, but if you call a database function like Prisma, you will get a Promise back, so you are kind of forced to stay "in Promise land", as there is no way to turn a Promise into a value. You can only chain functions, that should be executed with the value "in the future" (with then).
The last concept to understand is async/await. These async syntax is an addition to JavaScript syntax, that makes working with Promises easier. With await, you can stop the execution of a function until a value in a Promise arrives. Now, this looks like you are turning a Promise back into a value, but in reality, you function implicitly returns a Promise. For the VM to know about this, you have to state, that a function might use async by adding the keyword await in front of the function.
So when do you use async for a resolver? You could do it all the time, and the code would be correct. But doing it, even when you don't need to (e.g. you are not talking to a service) might have some performance implications. So it's better to only do it, if you really want to use the await keyword somewhere. I hope this can get you started with the concepts above, there is really a lot to learn. Maybe just go with your intuition and TypeScript errors until you deeply understand what is going on.

Does toPromise() unsubscribe from the Observable?

I have not been able to find any normative text to answer this question. I have been using this code pattern (this is in TypeScript in an Angular application):
observeSomethingFun$: Observable<Fun>;
...
async loadsOfFun() {
const fun = await this.observeSomethingFun$.toPromise();
// I now have fun
}
In general, Observables need to be unsubscribed from. This happens automatically when the Angular async pipe is used but what happens in this case? Does toPromise unsubscribe after emitting one value?
If not, how do I unsubscribe manually?
Update:
It turns out #Will Taylor's answer below is correct but my question needs some clarification.
In my case the Observable emits a never-ending stream, unlike for example Angular's HttpClient Observables that complete after emitting one value. So
in my case I would never get past the await statement according to Taylor's answer.
RxJS makes this easy to fix. The correct statement turns out to be:
const fun = await this.observeSomethingFun$.pipe(first()).toPromise();
The RxJS first operator will receive the first value and unsubscribe from the source Observable. it will then send out that value to the toPromise operator
and then complete.
No need to unsubscribe.
Which is convenient, as there is no way to unsubscribe from a promise.
If the Observable completes - the promise will resolve with the last value emitted and all subscribers will automatically be unsubscribed at this point.
If the Observable errors - the promise will reject and all subscribers will automatically be unsubscribed at this point.
However, there are a couple of edge cases with toPromise in which the behavior is not completely clear from the docs.
If the Observable emits one or more values but does not complete or error, the promise will neither resolve or reject. In this case, the promise would hang around in memory, which is worth considering when working with toPromise.
If the Observable completes but does not emit a value, the promise will resolve with undefined.
First of all, thank you for this question and answer, I wrongly assumed toPromise() knew what it was doing in all scenarios and would unsubscribe when that observable completes (even if it is an observable stream)
So I will just say that it doesn't hurt to pipe all of your observables before using .toPromise()
I just went through a big ordeal of stepping through our app for memory leaks and found the above answer by Will to be good. The elaboration on the actual question was exactly the same issue I was running into.
We are stepping through each observable in the app right now and we use either
pipe(take(1)) which is equivalent to pipe(first()).
or we use pipe(takeUntil(this.destroyed)) where this.destroyed.next(true) is called when we destroy our particular component or service.
We use take() to keep our verbiage consistent so we can search for take or takeUntil across various components.
Long story short, yeah you might take a very slight performance hit piping your observables at each instance, but I highly recommend doing so in order to prevent any unwanted app-wide memory leak hunts. Then maybe if you have the time you can step through each one and see where .toPromise() actually unsubscribes correctly for you.

How to cancel http requests made by Apollo (angular) client?

I noticed that when I unsubscribe from query, http request is still executing and not being canceled. Also tried to use AbortController but without any luck. How does one cancel http requests made by Apollo client?
This is an old question, but since I just wanted to do the same and managed to do it with the latest Apollo Client (3.4.13) and Apollo-Angular (2.6.0), you need to make sure that you're using watchQuery() instead of query(), and then call unsubscribe() on the returned Apollo subscription from the previous request. The latter implies of course that you should store somewhere the subscription object that you want to abort.
This is an old question, but I spent two days on this bananas problem and I want to share for posterity.
We're using Angular and GraphQL (apollo-angular and codegen to make GraphQL services) and we opted for an event-driven architecture using NgRx to send events and then perform http calls. When sending multiple identical events (but with different property values) we noticed we got stale data in some cases, especially edge cases like when 20+ of these identical events were sent. Obviously not common, but not ideal, and a hint of perhaps bad scale since we were going to need many more events in future.
The way we resolved this issue was by using .watch() instead of .fetch() on the GraphQL generated services. Initially, since .fetch() returned the same Observable as .watch().valueChanges, we thought it was easier and simpler to just use .fetch(), but their behavior seems much different. We were never able to cancel http requests performed by .fetch(). But after changing to .watch().valueChanges, the Observable acted exactly as http request Observables would, complete with -- thankfully -- cancelation.
So in NgRx, we swapped our generic mergeMap operator for the switchMap operator. This will ensure previous effects listening on dispatched events will be canceled. We needed no extra overhead, no .next-ing to Subjects, no extra Subscriptions. Just change .fetch() into .watch().valueChanges and then switchMap to your heart's content. The takeUntil operator will now also cancel these requests, which is our performed method of unsubscribing from Observables.
Sidenote: I'm amazed that this information was this hard to come by, and honestly this question and one GitHub issue was all I could find to intimate this discrepancy. Even now I don't quite understand why anyone would want .fetch() if all it does is perform an http call that will always resolve and then return an Observable that does not behave the way you expect Observables to behave.

Hystrix: Doing network call in getFallBack()

I've been playing around with Netflix OSS Hystrix and I am now exploring different configurations and possibilities to include it in my project. Among other things, my application needs to do network calls in HystrixCommand.getFallBack() ...
Now, I read that it is best-practice NOT to do network calls there and instead provide some generic answer (see Hystrix Wiki) and if it is really necessary to do this, one should use HystrixCommand or HystrixObservableCommand.
My question is, if I use HystrixCommand should I invoke it e.g., with HystrixCommand.run() or HysrixCommand.queue() or some other option?
Also, in my logs I've noticed that getFallBack() can have different calling threads (e.g., Hystrix-Timer, I guess this depends who interrupted the run method). Here I would like to know how shell calling HystrixCommand.run() from the fallback affect my performance, since the calling thread will be alive and blocked until that command finishes?
EDIT: With the fresh eyes on the problem, I am now thinking that the "generic answer" (mentioned above) could be some form of Promise i.e., CompletableFuture<T> in Java terminology. So returning the promise from the HystrixCommand.run() would allow the calling thread (Hystrix internal) to return immediately, thus releasing it. However now I am stuck on implementing this behavior. Any ideas?
Thanks a lot for any help!
Use a HystrixCommand's execute method. Example:
#Override
protected YourReturnType getFallback() {
return new MyHystrixFallbackCommand().execute();
}
If you want to work with async "promises" then you should probably implement a HystrixObservableCommand.

What is *like* a promise but can resolve mutliple times?

I am looking for a pub/sub mechanism that behaves like a promise but can resolve multiple times, and behaves like an event except if you subscribe after a notification has happened it triggers with the most recent value.
I am aware of notify, but deferred.notify is order-sensitive, so in that way it behaves just like an event. eg:
d.notify('notify before'); // Not observed :(
d.promise.progress(function(data){ console.log(data) });
d.notify('notify after'); // Observed
setTimeout(function(){ d.notify('notify much later') }, 100); // Also Observed
fiddle: http://jsfiddle.net/foLhag3b/
The notification system I'd like is a good fit for a UI component that should update to reflect the state of the data behind it. In these cases, you don't want to care about whether the data has arrived yet or not, and you want updates when they come in.
Maybe this is similar to Immediate mode UIs, but is distinct because it is message based.
The state of the art for message based UI updating, as far as I'm aware, is something which uses a promise or callback to initialize, then also binds an update event:
myUIComponent.gotData(model.data);
model.onUpdate(myUIComponent.gotData); // doing two things is 2x teh workz :(
I don't want to have to do both. I don't think anyone should have to, the use case is common enough to abstract.
model.whenever(myUIComponent.gotData); // yay one intention === one line of code
I could build a mechanism to do what I want, but I wanted to see if a pub/sub mechanism like this already exists. A lot of smart people have done a lot in CS and I figure this concept must exist, I just am looking for the name of it.
To be clear, I'm not looking to change an entire framework, say to Angular or React. I'm looking only for a pub/sub mechanism. Preferably an implementation of a known concept with a snazzy name like notifr or lemme-kno or touch-base.
You'll want to have a look at (functional) reactive programming. The concept you are looking for is known as a Behavior or Signal in FRP. It models the change of a value over time, and can be inspected at any time (continuously holds a value, in contrast to a stream that discretely fires events).
var ui = state.map(render); // whenever state updates, so does ui with render() result
Some popular libraries in JS are Bacon and Rx, which use their own terminology however: you'll find properties and observables.

Resources