In android, some codes, such as updating UI buttons, needs to be called in UI thread, however, before UI update, some task, such as getting response from internet, need to be done on another thread, here is the most common form of response callback I see:
public void httpResponseCallback(String responseString){ MyFragment.this.getActivity().runOnUiThread(new Runnable(){ @Override public void run(){ if(responseString==null || responseString.isEmpty()){ showErrorDialog(); }else{ List<String> nameList=this.parse(responseString); if(nameList==null){ showErrorDialog(); }else{ updateUI(nameList); } } } }); }
But I think this callback is not good enough, because some codes doesn't require to place inside runOnUiThread, so I think the following form is better:
public void httpResponseCallback(String responseString){ if(responseString==null || responseString.isEmpty()){ MyFragment.this.getActivity().runOnUiThread(new Runnable(){ @Override public void run(){ showErrorDialog(); } }); }else{ final List<String> nameList=this.parse(responseString); if(nameList==null){ MyFragment.this.getActivity().runOnUiThread(new Runnable(){ @Override public void run(){ showErrorDialog(); } }); }else{ MyFragment.this.getActivity().runOnUiThread(new Runnable(){ @Override public void run(){ updateUI(nameList); } } } }
After refactoring, at start, I think it would be better, because I think:
- It reduce unnecessary workload on UI thread
- It give hints to other teammates that which functions or codes need to run on UI thread
But later when I read the code again, I found the code is far longer than the original one because of extra runOnUiThread to type, so my question is, is wrapping all codes into runOnUiThread better than using runOnUiThread only on UI related code?