Can I do a synchronous request with volley?

后端 未结 8 1725
执念已碎
执念已碎 2020-11-22 11:02

Imagine I\'m in a Service that already has a background thread. Can I do a request using volley in that same thread, so that callbacks happen synchronously?

There ar

8条回答
  •  生来不讨喜
    2020-11-22 12:04

    I use a lock to achieve that effect now im wondering if its correct my way anyone want to comment ?

    // as a field of the class where i wan't to do the synchronous `volley` call   
    Object mLock = new Object();
    
    
    // need to have the error and success listeners notifyin
    final boolean[] finished = {false};
                Response.Listener> responseListener = new Response.Listener>() {
                    @Override
                    public void onResponse(ArrayList response) {
                        synchronized (mLock) {
                            System.out.println();
                            finished[0] = true;
                            mLock.notify();
    
                        }
    
    
                    }
                };
    
                Response.ErrorListener errorListener = new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        synchronized (mLock) {
                            System.out.println();
                            finished[0] = true;
                            System.out.println();
                            mLock.notify();
                        }
                    }
                };
    
    // after adding the Request to the volley queue
    synchronized (mLock) {
                try {
                    while(!finished[0]) {
                        mLock.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    

提交回复
热议问题