Search code examples
androidandroid-architecture-components

Android Architecture Components - Best practices


I have tried Android Architecture Components and I have a few questions about best practices.

  1. How do you deal with errors?

For example, I can have a few types of error. It can be "No Internet" error or other (as exception) and can be error-response from server (as string or json).

Do you create a few LiveData for every type of error? Or do you create a wrapper-object with the result and two types of errors (string/exception) and use only one LiveData? What's better? A wrapper-object with 3 fields seems to be complicated.

  1. Is it ok to parse result and errors in View? Does View make too much work, isn't it? How do you think? Also, where do you parse json-errors?

  2. Is it ok to use R.string in ViewModel? Or is it badly? If it is, how can I fetch strings from R.string for ViewModel?

Thanks


Solution

    1. I suggest a wrapped generic object, like:

      public class ResultBase { private String _error;

      public ResultBase(){}
      
      public ResultBase(String error){
          _error = error;
      }
      
      public boolean isSuccess(){
          return _error == null || _error.isEmpty();
      }
      
      public String getError(){
          return _error;
      }
      
      public void setError(String error){
          _error = error;
      }
      

      }

      public class Result extends ResultBase {

      private T mData;
      
      public T getData(){
          return mData;
      }
      
      public Result(String message){
          super(message);
      }
      
      public Result(T data){
          mData = data;
      }
      
      @Override
      public String toString() {
          return isSuccess() ? "Ok" : "ERROR: " + getError();
      }
      

      }

    2. Server response should be parsed in a service layer. So, a View subscribe on LiveData from ViewModel, ViewModel in turn call the Service layer. So, "View" obtain fully prepared data with or without an error sign.

    3. It's ok. R.string it is just a constant. You can obtain it like getApplicationContext().getString(strId)