-1

I want to hit multiple API to get some data from the server, but When I try to hit multiple API in the same time it has a chance to interrupt each other, so sometimes one of those APIs doesn't work, Any Solution?

I set it on the OnCreate method

//API1
mainActivity_.rncryptorLoadGameRating(mGameID);
//API2
mainActivity_.rncryptorLoadGameRatingComment(mGameID, 0);
  • If you are familiar with `RXJava` you can use Zip operator to do this .. See [This](https://stackoverflow.com/questions/36474120/how-to-make-multiple-request-and-wait-until-data-is-come-from-all-the-requests-i). – ADM Jan 21 '20 at 04:15

1 Answers1

2

I am gonna go with some assumptions first since the definition of the problem is not very clear.

I'm not sure how exactly two different consecutive API calls can interact and disturb each other. It's very likely two calls in the same instance are in some kind of race condition. It means something is broken in your code. Architecture-wise, two distinct API calls must not interrupt each other ever and never.

If it is the case that concurrent call of two methods / APIs may interrupt each other, one naive approach would be to lock methods rncryptorLoadGameRating(mGameID) and rncryptorLoadGameRatingComment(mGameID, 0) with the same intrinsic lock using synchronized in java and GuardedBy("this") so this way, two methods will not be called in parallel, they will be called in sequence. Only one API call can have lock and modify the state of the object and release the lock so the other api can have it and work with the object state. As far as I understand that parallel call of two methods are in race condition in object state of mainActivity_, that's why they are interrupting one another.

public class MainActivity {

    @GuardedBy("this") int yourStateVariable;

    synchronized void rncryptorLoadGameRating(int mGameID){
        //Definition of method
    }

    synchronized void rncryptorLoadGameRatingComment(int mGameID, int number){

    }
}

You need to guard the state variables with the lock. In addition, encapsulate your state in the api methods' object. Performance wise, it is not a good approach but works fine. You may want to look at the following as well: mutex, semaphores or latches, future-promises in Java. I could write the examples here for them too. However, it will be too much. Please also check thread confinement and stack confinement to achieve better performance.

If it is Kotlin code, I would recommend checking in coroutines.

Farruh Habibullaev
  • 2,342
  • 1
  • 26
  • 33