1

I want to run jobs in serial queue(Wait for first job to start second). I am using android priority queue library which allows you to run jobs in serial by setting same group id but it dont work in my case.

I have added three jobs in queue

jobManager.addJobInBackground(new FetchQuestionsJob(this)); jobManager.addJobInBackground(new FetchUsersJob(this)); jobManager.addJobInBackground(new FetchTeamsJob(this));

My all three jobs are similar to this class but all of the jobs run concurrently. I receive response from FetchUsersJob/FetchTeamsJob earlier than FetchQuestionsJob.

public class FetchQuestionsJob extends Job{

Context context;
public FetchQuestionsJob(Context context){
    super(new Params(9).requireNetwork().setGroupId(FETCH_REQUESTS));
    this.context = context;
}

@Override
public void onAdded() {

}

@Override
public void onRun() throws Throwable {
    new FetchQuestionsApi(context);
}

@Override
protected void onCancel(int cancelReason, @Nullable Throwable throwable) {

}

@Override
protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {
    return null;
}

FetchQuestionApi

public class FetchQuestionsApi implements IDataReceiveListener {

VolleyNetworkController networkController;

Context context;
Realm realm;

public FetchQuestionsApi(Context context) {
    this.context = context;
    networkController = new VolleyNetworkController(context);
    networkController.getRequest(URL_GET_QUESTIONS, null, null, this);
}

@Override
public void onDataReceived(JSONObject jsonObject) {

    try {

        if (jsonObject.getBoolean(RESPONSE_SUCCESS)) {
            JSONArray data = jsonObject.getJSONArray("Data");
            Gson gson = new Gson();
            Question[] question = gson.fromJson(data.toString(), Question[].class);
            realm = Realm.getDefaultInstance();
            realm.beginTransaction();
            realm.copyToRealmOrUpdate(Arrays.asList(question));
            realm.commitTransaction();
            Question specificCountry = realm.where(Question.class).findFirst();
            String id = specificCountry.getId();
            Log.d("", jsonObject.toString());
            AppController.getInstance().getJobManager().addJobInBackground(new FetchUsersJob(context));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

@Override
public void OnError(String message) {

}
  • There are a couple of different ways to handle this. If you need those requests to run in sequence. You could not make them jobs but just pojos, and make the synchronous network requests for each of the pojos in question. JobManager by it's design will run jobs in parallel if there is an open slot on the thread pool for it to do so. – kingargyle Apr 11 '17 at 13:02

1 Answers1

0

Try to use .groupBy(FETCH_REQUESTS) instead of .setGroupId(FETCH_REQUESTS). It works fine in my case.

isabsent
  • 3,683
  • 3
  • 25
  • 46