0

Let's understand the scenario, I have to call a third party API in one of the API calls to my server (let say A) from the mobile app. That third party API takes almost 12-15 seconds to execute. However, in the next consecutive API call to my server (let say B), I need to have the response of that third party API before start processing.

Here, It's important for me to call that third party API in a new thread in the first API call to my server i.e. A. So that I can efficiently use the processing time for my second API i.e. B as the mobile user has to give certain inputs b/w these two API's A & B.

The solution I have in my mind is that I will hit the third party API in the new thread, will save the thread reference in a variable and pass it in the response of my first API call like

@th_ref = Thread.new do

// serive for third party api

end

json.thread_ref @th_ref

In the next API call i.e. B, I will get this reference in a body and then I will join my main thread with the previous thread so that B does not start work until I get the third party API response.

But with the above solution, I get the thread_ref in String class in the second API's body like

"#<Thread:0x00007fc84e316e38@(pry):157 run>"

and I have to change it back to Thread class so that I can use functions like thread_ref.join or thread_ref.alive?

Kindly suggest how can I achieve this conversion and am I using the right approach for my problem?

  • were you able to find a solution for this? – Carl V. Oct 04 '21 at 08:45
  • @CarlV. Not exactly, but I came up with a **"solution"** to solve the urgent issue at that time. Major steps were – Hamza Shamshad Oct 04 '21 at 21:18
  • **1**- I passed the thread reference (that called the 3rd party API ) to the API. **2**- Then after next 2-3 APIs or whenever it's needed, mobile app sends me back that thread_reference in the request body. **3**- From there, I manipulated the thread_reference status from "run" to "sleep". **4**- Then I searched for this thead in the list thead_list using `prev_thread = Thread.list.select {|thread| thread if thread.to_s == thread_ref_from_api}` **5**- From there, I bind the main thread with the previous thread, that called the 3rd API before, to see if its execution is completed or not. – Hamza Shamshad Oct 04 '21 at 21:18
  • I hope you could find a better solution than this :) – Hamza Shamshad Oct 04 '21 at 21:19

0 Answers0