記錄多個請求狀態

//可處理多個併發請求,每個網絡請求都有以下4個狀態,使用兩位標記。我們傳入的每個index表示一個網絡請求。每個網絡請求的Index可依次爲0,2,4,6.....

public class LoadingState {
    public static final int STATE_INIT = 0;
    public static final int STATE_LOADING = 1;
    public static final int STATE_SUCCESS = 3;
    public static final int STATE_FAILD = 4;
    
    public static final int STATE_MASK = 3;
    
    public static int resetState(int loadingRecord,int index){
        loadingRecord = loadingRecord&(~(STATE_MASK<<index));
        return loadingRecord;
    }
    
    public static int startLoading(int loadingRecord,int index){
        loadingRecord = resetState(loadingRecord, index);
        loadingRecord = loadingRecord | (STATE_LOADING << index);
        return loadingRecord;
    }
    
    public static int loadFinished(int loadingRecord,int index,boolean flag){
        loadingRecord = resetState(loadingRecord, index);
        int result = flag ? STATE_SUCCESS :STATE_FAILD;
        loadingRecord = loadingRecord | (result << index);
        return loadingRecord;
    }
    
    public static int getLoadingState(int loadingRecord,int index){
        return (loadingRecord >> index) & STATE_MASK;
    }
    
    public static boolean isLoading(int loadingRecord){
        boolean result = false;
        for(int i =0;i<Integer.SIZE/2;i++){
            int loadingState = (loadingRecord>>(i*2)) & STATE_MASK;
            if(loadingState == STATE_INIT)
            {
                continue;
            }            
            result = loadingState == STATE_LOADING;
            if(result){
                break;
            }
        }
        return result;
    }
}

 

loadingRecord初始化爲0,  A請求的index爲0,B請求的index爲2.

A請求發起的時候調用LoadingState.startLoading(loadingRecord,0);

B請求發起的時候調用LoadingState.startLoading(loadingRecord,2);

A請求完成的時候調用LoadingState.loadFinished(loadingRecord,0,true);

 

判斷某個請求的狀態,調用getLoadingState方法。

往往頁面有多個請求,需要判斷是否處於加載狀態,調用isLoading方法,待所有請求都結束,再隱藏正在加載的提示,或進行後續流程。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章