How to send asynchronous http request using rxjava
Does anyone know how I can write something like this where it sends an HTTPRequest asynchronously using retry logic in rxjava?
HTTP_CLIENT.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString())
.thenApplyAsync(CompletableFuture::completedFuture)
.exceptionallyAsync(throwable -> {
CompletableFuture<HttpResponse<String>> failure = new CompletableFuture<>();
return retrySend(httpRequest, throwable, 1, failure);
})
.thenComposeAsync(Function.identity())
.thenAcceptAsync(httpResponse -> {
errorHandler.accept(httpResponse);
});
private CompletableFuture<HttpResponse<String>> retrySend(HttpRequest request,
Throwable throwable, int retryCount, CompletableFuture<HttpResponse<String>> failure) {
if (retryCount > MAX_RETRIES) {
failure.completeExceptionally(throwable);
return failure;
}
HTTP_CLIENT.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.handleAsync((httpResponse, throwable1) -> {
if(httpResponse == null) {
try {
throw new ClientException(throwable.getMessage() +
"Status code: 500. " + "Retry sending the message");
} catch (Exception e) {
LOGGER.debug(e.getMessage(), e);
}
return retrySend(request, throwable1, retryCount + 1, failure);
}
else {
LOGGER.debug("Successful. Status Code: " +
httpResponse.statusCode());
LOGGER.debug("Body: " + httpResponse.body());
retu rn CompletableFuture.completedFuture("Message was delivered");
}
});
return failure;
}
do you know?
how many words do you know
See also questions close to this topic
-
Read each name in Array list to create seperate object for
I have a file that has student names, age, and an id number. I have a student class that holds the everything above for each student object. I stored all the names, id numbers. and age separately in an array list. Now im trying to assign the info to create a student object.
public class Student { private String lName; private int idNumber; private int age; public Student() { lName = ""; idNumber = 0; age = 0; } public Student(String l, int i, int a) { lName = l; idNumber = i; age = a; } public void setName(String last) { lName = last; } public String getName() { return lName; } public void setIdNum(int num) { idNumber = num; } public int getIdNum() { return idNumber; } public void setAge(int a) { age = a; } public int getAge() { return age; } }
My Text File looks something like this: This info is stored in parallel array lists. I don't quite get how to implement this into an object to pass it into my second contractor method.
Josh 2134 19 Smith 5256 21 Rogers 9248 19 Andrew 7742 20
Here's what I've tried;
public static void main(String[] args) { String file = "studentData.txt"; Scanner reader = new Scanner(file); ArrayList<String> lastNames = lNames(file); ArrayList<Integer> idNumbers = idNum(file); ArrayList<Integer> ageList = ages(file); Scanner input = new Scanner(System.in); Student s1 = new Student(); // confused about how to implement this constructor with the textile info for (int i = 0; i<idNumbers.size(); i++) { Student user = new Student(lastNames.get(i), idNumbers.get(i), ageList.get(i)); } //user enters idNumber to display age System.out.println("Enter ID Number"); //exception handling to be added int idNum = input.nextInt(); for (int i = 0; i<idNumbers.size(); i++) { if (idNum == idNumbers.get(i)) { s1.setAge(ageList.get(i)); System.out.println(s1.getAge()); } } }
-
Using EdittextPreference for Goto search
sorry for my poor English. I want to use EditTextPreference in my bottom nav like the pic below, ![screenshot][1]
I have recycleview xml in my project with in many sub cardview layouts(which is scrollable) and I want to create item in the bottom nav which is called "Goto". When the "Goto" item is clicked i want it to pop-up like the screenshot. And when user enters a number(according to the cardviews i.e if the number of cardview is 40 user must enter 1-40) I want to search the cardview by its ID. Thank you and I hope u got it, If u have any questions let me know [1]: https://i.stack.imgur.com/grK8P.jpg
My xml format look like this. As you see in the blow since the cardviews are huge in number it is not cool to scroll all the way down that is why i need Goto item in the bottom nav to search it by its ID when the user click number in the EditTextPreference as u see in the screenshot. i.e The screenshot is not from my app
<LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> <LinearLayout> <androidx.cardview.widget.CardView> <RealtiveLayout> <Textview/> <RealtiveLayout> </androidx.cardview.widget.CardView> </LinearLayout> .. .. .. .. many more..
-
How to get remaining time of the day in java?
I would like to calculate the time remaining for next day 00:00:00 from the current date time.
For e.g. time difference between 2
022-05-07T05:49:41.883807900Z
and2022-05-08T00:00:00Z
Expected answer:
18:10:19
or 65419 (in seconds).How can I achieve this with efficiently using java 8?
-
Redirect inside async function
I have a function for creating a Stripe.com checkout session:
@csrf_exempt def create_checkout_session(request): if request.method == 'GET': domain_url = 'https://example.com/' stripe.api_key = settings.STRIPE_SECRET_KEY try: order = request.user.profile.order_set.get(ordered=False) all_in_stock = True for orderitem in order.orderitem_set.all(): if orderitem.item.in_stock >= orderitem.quantity: pass else: all_in_stock = False break if all_in_stock: line_items = [] for orderitem in order.orderitem_set.all(): line_item = { 'name': orderitem.item.item_name, 'quantity': orderitem.quantity, 'currency': 'usd', 'amount': int(orderitem.item.price * 100), } line_items.append(line_item) orderitem.item.in_stock -= orderitem.quantity orderitem.item.save(update_fields=['in_stock']) if order.shipping_address.state == 'IL': line_item = { 'name': 'Sales tax', 'quantity': 1, 'currency': 'usd', 'amount': int(order.get_sales_tax() * 100), } line_items.append(line_item) checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.profile.id, success_url=domain_url + 'store/success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'store/cancelled/', payment_method_types=['card'], mode='payment', line_items=line_items, customer_email=request.user.email, expires_at=int(time.time() + 3600), ) return JsonResponse({'sessionId': checkout_session['id']}) else: messages.error(request, "Not enough items in stock to fulfill the order") return redirect("store:order-summary") except Exception as e: return JsonResponse({'error': str(e)})
It is executed with this script:
fetch("/store/config/") .then((result) => { return result.json(); }) .then((data) => { const stripe = Stripe(data.publicKey); document.querySelector("#stripeSubmitBtn").addEventListener("click", () => { fetch("/store/create-checkout-session/") .then((result) => { return result.json(); }) .then((data) => { console.log(data); return stripe.redirectToCheckout({sessionId: data.sessionId}) }) .then((res) => { console.log(res); }); }); });
I want to add the functionality to check that all items are still in stock, and if not abort the session. I am new to JS. I understand that simple redirect doen't work because the function is executed asynchronously, but I don't know how to do it correctkly. What is the right way to implement it?
-
How to add CancellationToken on Unity Web request?
I wrote the following code that successfully downloads a photo from the link. But I want to set a
cancellationToken
for the request that can be activated by pressing thex
key. please guide me.private async void GetImage() { var request = UnityWebRequest.Get(requestURI); await RequestEnd(request); // add cancellation when I press any key.. var date = request.downloadHandler.data; texture2D = new Texture2D(1, 1); texture2D.LoadImage(date); } private static async Task RequestEnd(UnityWebRequest request) { request.SendWebRequest(); Debug.Log("Request Send"); while (!request.isDone) await Task.Yield(); }
-
How to do multiple aio_writes to file
When doing multiple aio_writes to file is it necessary to wait (e.g. aio_suspend or other) before starting the next one? From the documentation it says that writes are enqueued so does that mean they are written in order? Also, I can track the offset and make sure nothing is ever overwritten (I'm assuming that a failed write could leave a gap in this case).
-
Can RxJava be used to send messages only to the most recent subscriber?
I've been given a requirement that when there are multiple observers, only the most recent subscription should receive messages. I'll illustrate with sloppy code examples.
val fooDisposable = mostRecentSubscriberObservable.subscribe(this::foo)
Any time
mostRecentSubscriberObservable
emits an item,foo()
is called.Now this runs:
val barDisposable = mostRecentSubscriberObservable.subscribe(this::bar)
Now whenever an item is emitted,
bar()
is called, becausebarDisposable
is the most recent subscriber.foo()
is NOT called.Now this runs:
barDisposable.dispose()
Now whenever an item is emitted,
foo()
is called. Now thatbarDisposable
is gone,fooDisposable
is the most recent subscriber, and receives the item.Short of creating a custom
Subject
class (which seems rather complex), is there a way to do this - any existingSubject
or combination of operators which would accomplish it? I can't seem to find anything like that. -
Repeat Rxjava chain
I am getting data then I am doing an async request to check flag and if it is false, I want to repeat this step for 5 times with 1 sec delay until it gets true and continue processing or throw exception.
return getData() .flatMap(data -> checkFlag() .map(b -> { if (b) { return data; } else { throw new Exception(); } })) .retryWhen((Flowable<Throwable> f) -> f.take(5).delay(1000, TimeUnit.MILLISECONDS)) .flatmapCompletable(data -> sendEvent(data)) Maybe<Dto> getData(); Maybe<Boolean> checkFlag(); Completable sendEvent(Dto dto);
I am using retryWhen(), but because of it I have to throw Exception on false case. Maybe there is a better way to do it and to avoid working from exception? If it is not, then how can I retry only for specific Exception?
.retryWhen(e -> e.flatMap(error -> { if (error instanceof CustomException) { return Flowable.just(null);//doesn't trigger repeat } return Flowable.error(error); }).take(5).delay(1000, TimeUnit.MILLISECONDS))
-
Java CompletableFuture using allOf : if one thread throws exception, how to immediately stop execution of all threads?
// assume: serviceCall1 throws an exception after 1s, servserviceCall2 runs 10s without exception CompletableFuture<String> serviceCall1Future = serviceCall1.execute(); CompletableFuture<String> serviceCall2Future = serviceCall2.execute(); CompletableFuture<Void> allOffFuture = CompletableFuture.allOf(serviceCall1Future, serviceCall2Future); // does not work, will be called after thread 2 has finished allOffFuture.exceptionally( ex -> { allOffFuture.cancel(true); return null; } ); try { // waiting for threads to finish allOffFuture.join(); } catch (CompletionException e) { // does not work, here we come after thread 2 has finished allOffFuture.cancel(true); }
If one thread throws an exception, in my case it doesnt make any sense for the other thread(s) to keep on running, so I want them both (all in case of more than 2 threads) to stop . How can I achieve that ?
-
Which ExecutorService is best for blocking IO tasks
Let's imagine that we have n independent blocking IO tasks e.g. tasks for rest-call to another server. Then all answer we need to combine. Every task can be processing over 10 second.
- We can process it sequentially and spent ~n*10 second at the end:
Task1Ans task1 = service1.doSomething(); Task2Ans task2 = service2.doSomething() ... return result;
- Another strategy is to process it in parallel manner using CompletableFuture and spent ~ 10 second on all task:
CompletableFuture<Task1Ans> task1Cs = CompletableFuture.supplyAsync(() -> service1.doSomething(), bestExecutor); CompletableFuture<Task2Ans> task2Cs = CompletableFuture.supplyAsync(() -> service2.doSomething(), bestExecutor); return CompletableFuture.allOf(task1Cs, task2Cs) .thenApply(nothing -> { ... // combine task1, task2 into result object return result; }).join();
Second approach has benefits, but I can't understand which type of thread pool is the best for this kind of task:
ExecutorService bestExecutor = Executors.newFixedThreadPool(30) /// or Executors.newCachedThreadPool() or Executors.newWorkStealingPool()
My question is which ExecutorService is best for process n-parallel blocking IO tasks
-
Android ReactiveX - Is it possible to have an observer of 2 possible response types?
Here is what I'm starting with. The Clover API that I'm calling returns 2 different possible responses. A "PaymentSuccessResponse" if the credit card was authorized and a "PaymentFailResponse" if the response was a rejection of the card or if the user canceled the transaction.
Since these two models are completely different is there a way to try and observe on a success, but if that fails observe as a fail?
val apiCloverService = retrofit.create(ApiCloverService::class.java) val cloverOperationResponse = apiCloverService.postPayment(paymentPost, authHeader, lastReaderDeviceID, posID, paymentPost.externalPaymentId) cloverOperationResponse.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .timeout(40, TimeUnit.SECONDS) .subscribe(object : SingleObserver<Response<PaymentFailResponse>> { override fun onSubscribe(d: Disposable) { disposables.add(d) } override fun onSuccess(cloverOperationFailResponse: Response<PaymentFailResponse>) { processSuccess(cloverOperationFailResponse.body()) } override fun onError(e: Throwable) { processFailure(e, "ping") } })
-
Reduce custom object using RxJava
I'm using RxJava, I have a list of Point and i want to calculate the distance between each point and get the sum.
The point class look like this
public class Point { public double x; public double y; }
So i need to map and reduce at same time, but i didn't found a solution.
public Observable<Double> totalDistance(Observable<List<Point>> obs) { return obs.reduceMap(new ArrayList<Integer>, (list, pointA, pointB) -> distance(pointA, pointB)). ? }
What its the most efficient way to do it (or at least a solution that works) ? Which operator should i use ?
To give a more concrete example, here is what I have and what I want:
Point a (45, 32) Point b (56, 75) Point c (44, 53) Point d (42, 54) Point e (42, 55) a to b = 10m b to c = 15m c to d = 25m d to e = 10m Result = 60m
In reality my points are GPS positions and I use the haversine formula to calculate the distance between two positions.
I use observables because the list of points to be calculated is updated sometime. In fact every x points the user has reached, I have an instruction to send. After sending the instruction, a new list of points until the next instruction is emit.
-
What is a Single<Int>! and how can I instantiate a variable as it
I'm trying to solve some test issues and I'm getting the error:
The integer literal does not conform to the expected type Single!
I've never worked with Single<> and I haven't been able to found how to instantiate a variable as one in Kotlin.