what is different at httpService.get and httpService.axiosRef.get #nestjs/axios? - axios

I'm new to nestJS and RxJS and try to use axios for http request.
I noticed there're two options when using axios API.
using HttpService.get. it returns Observable and RxJS should be used together.
using HttpService.axiosRef.get. it returns Promise.
What is diff between 2 options??
ex) performance, catching error. etc.....
Thank you.

HttpService#get is the observable wrapped axios call. HttpService#axiosRef.get is the raw axios.get method, no observables added, just promises.
You can use either, just depends on your preference. You can also turn observables into a promise via lastValueFrom(observable) or a promise into an observable using from(promise)

Related

In RxSwift, how can I unit test that an observable sent no event?

I am new to testing un RxSwift.
I manage to test that an Observable emits values with RxBlocking. But I can't find the syntax to make a test pass if an Observable did not send any value.
I think I should use toBlocking(timeout: ),but I can't find how (I have an error that it timed out, but the test fail).
Thank you for your help
Does your observable complete? It looks like you're testing to see if the observable emits any events not values
Assuming you are testing on the XCTest Framework,
If you are testing to see if the observable emits no elements before it completes,
XCTAssertNil(try observable.toBlocking().first())
If you are testing to see if the observable does not emit any elements, nor completes
// Check error if necessary
XCTAssertThrowsError(try observable.toBlocking(timeout: timeout).first())

reactive 4.2.0 net Subject<T> ReplaySubject<T>

I am using ReplaySubject as a pipe when I feed the Observer with OnNext messages and then I subscribe to the message in another part of the code.
I tried ISubject first, by using Subject.Create(observer:, observable:) but this seems to do nothing, or in other words, the Observer is a sink that goes nowhere. Is there some code that will make the Subject do something pipe-like. For example, I want to inject onNext messages with a integral countN and I want the observable to broadcast N-many 0.00E0(s) in sequence.
UPDATE:
It seems I need to implement the ISubject interface. Is there source code for a simple implementation that functions the same as ReplaySubject, with simple, proper memory handling of buffer size and Observer collection and Disposable return object.
Ok, so you use
new Subject<Int32>()
to get a subject that is a pipe-line.
Someone care to explain what Subject.Create does?
Can you inherit from Subject or ReplaySubject? Should you be able to?

Create BehaviorSubject from Observable

Say I have an observableA which gets data from network and emits it, if I do subscription to this observable each time it tries to request data from network which is heavy.
I want to create BehaviorSubject and connect it to observableA, so that any other threads/objects will subscribe to BehaviorSubject in order to get latest emitted data.
So far I couldnt manage it to code. I cannot create empty BehaviorSubject and call inside observableA, because they are not related to each other.
I cannot subscribe to observableA and get BehaviorSubject as observer, any idea how can I accomplish it? or maybe even better?
You can use multicast. E.g.,
Observable<String> o = ...;
ConnectableObservable<String> co = o.multicast(BehaviorSubject.<String> create());
co.connect();
co.subscribe(...);
co.subscribe(...);
co.subscribe(...);
I had similar scenario in javascript where I wrapped promise within Rx and I didn't want to make network call again when I subscribe to observable. This is how I ended up implementing:
subject = new Rx.AsyncSubject();
observable = Rx.Observable.fromPromise(....).subscribe(subject);
You can now consume the promise response as subject.subscribe(...) and it will always emit promise result from subject as we are using AsyncSubject (AsyncSubject - Represents the result of an asynchronous operation. The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers).
In Rx.NET we'd use one of the Publish overloads that accepts an initialValue parameter. Essentially, it's just a shorter way of doing a multicast like zsxwing described. I'm not sure whether Rx.Java offers these overloaded Publish methods.

GWT how to do async response with Http promise like in Play!Framework

I am coming from Play!Framework world into a GWT application.
I need to invoke an HTTP response from my GWT server.
In Play!Framework 1 I would simply "await" an WS.get.async result
Promise<HttpResponse> futureResponse = WS.url(
"http://www.google.com"
).getAsync();
await(futureResponse);
And in play!framework2 I simply return an async response.
return async(
WS.url(feedUrl).get().map(
new Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("Feed title:" + response.asJson().findPath("title"));
}
}
)
);
both code snippets are from Play!Framework's documentation.
How can I achieve the same result in GWT backend?
There's nothing like a "GWT server" or "GWT backend". If you're using GWT-RPC or RequestFactory, it's all servlet-based, without support for async processing; and GWT only provides the mean to process the client's requests, what you do on the server-side is entirely up to you, and is play Java (assuming GWT-RPC or RequestFactory, and their built-in implementations).
If you have an HTTP client library that returns a java.util.concurrent.Future (or something equivalent), then you can just do return theFuture.get(); to wait for the HTTP request to complete.
Most HTTP client libs in Java a synchronous (blocking) though, so you don't even need to think about asynchronicity. If you want to do multiple things simultaneously, some libs can work async but many (if not most) use a callback rather than returning in Future. You can then use locks to await completion, or use something like Guava's SettableFuture (set its value from the callback, get its value when needed and it'll block until the value is set)
Note: most, if not all, other answers deal with client-side code, not server-side code as you asked about.
GWT doesn't have Promises, but you can use gwtquery which apart from other features has a Promises implementation based on Promises/A+.
Edit: Notice that GWT is client-side centric, so this approach in just for the browser js runtime.
Your example could be written in this way:
import static com.google.gwt.query.client.GQuery.*;
import com.google.gwt.query.client.*;
// Using $$ to create a jso with the parameters for the ajax method
// You can though use Settings.create() to use a java builder instead.
Promise gettingInfo = ajax($$("url: rest_service.js, type: post, dataType: json, data: {foo: bar}"));
// You can use the promise as many times as you need it,
// it would always maintain the status and server data.
gettingInfo.done(new Function(){public void f() {
Properties jsonResponse = arguments(0);
Window.alert("Feed title:" + jsonResponse.get("title"));
}});
Note that GQuery methods returns a Promise for certain methods (ajax, animations, etc).
In this response there is another code example of using gquery promises.
In GWT you need a lot of boiler plate code to do an Async Server Side call, and phylosophy is very different in GWT compare to Play
The only thing you can do is someting like :
myServiceAsync.myService(myRequest, new AsyncCallBack<myResponse>(){
onSuccess(MyResponse response){
// do your stuff
}
onFailure(Throwable e){...}
}
for this to work you need a lot of stuff:
a RemoteServlet that implements your service (Synchronous interface of point 2)
two interfaces one Synchronous and another Asynchronous
the instanciation of the Synchronous service on the client side that return the asynchronous version of your service
Hope it helps
Further explanation on GWT homepage : http://www.gwtproject.org/doc/latest/DevGuideServerCommunication.html
You could use GWTP https://code.google.com/p/gwt-platform/
It has a simple dispatch, with action response tuple that is easy to use.
Example: https://github.com/ArcBees/GWTP/wiki/RPC-Dispatch
That code was forked from GWT-Dispatch: https://code.google.com/p/gwt-dispatch/
That is also an alternative if you don't want to use a full MVP framework.

How do I go about returning errors from a REST request to django-tastypie?

I have a simple form that passes data to backbone, which in turn, submits requests to a tastypie REST API. The validation is done server side.
When a specific field has an error, how would I go about returning that error and handling it in backbone so it can be displayed alongside the field? Keeping in mind that backbone is expecting a model in return and not a bunch of errors (returning an array of errors with the associated fields sounds fine but I have a special backbone parse method that gets the objects out of the tastypie response - sending back random stuff will probably make it choke...?).
Confused as to why this isn't a common task to do.
Tastypie should be returning your validation errors with an http error-level code 4xx, not a success-level code 2xx.
Because of this, Backbone should be triggering the error callback, not the success callback.
Because the error callback is being triggered, Backbone doesn't invoke parse or anything else that happens on success.
So, you need to create a handler for tastypie errors, and pass that error handler function as the error callback.
From there, you can manually parse the body of the response and deal with the errors however you see fit for your app.