Friday, 5 July 2019

MVVM Design Pattern with data saving on orientation change.

Here is a simple basic  example that how in MVVM design patter we can save the data on orientation change.

Here i am calling a API which will give me the data using Retrofit,LiveData,RxJava and MVVM pattern.

1. app-Gradle :-
// to use retrofit2 notation like @SerializedName("") @Expose    
implementation 'com.squareup.retrofit2:retrofit:2.5.0'    
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'    
implementation 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
//to use viewModelProviders.of    
def lifecycle_version = "1.1.1"    
implementation "android.arch.lifecycle:extensions:$lifecycle_version"    
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version"   
 implementation 'com.android.support:recyclerview-v7:28.0.0'
// For using AndroidSchedulers for io    
implementation 'io.reactivex:rxandroid:1.2.1'    
// for the using of HttpLoggingInterceptor    
implementation 'com.squareup.okhttp3:okhttp:3.10.0'    
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.github.bumptech.glide:glide:4.9.0'
2. Create model with your aPI response like following  :-
API name:- https://jsonplaceholder.typicode.com/photos
@SerializedName("albumId")
private int albumId;

@SerializedName("id")
private int id;

@SerializedName("title")
private String title;

@SerializedName("url")
private String url;

@SerializedName("thumbnailUrl")
private String thumbnailUrl;
3. Create interface name as APIService :-
public interface APIServices {
    @GET("{photos}")
    Observable<List<PhotoResponse>> getPhotos(@Path("photos") String photos);
}

4. Create NetworkManager  :-
public class NetworkManager {
    private static final String BASE_URL = "https://jsonplaceholder.typicode.com/";

    public static APIServices getRetrofitServices() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit.create(APIServices.class);
    }

}

5. MainActivityRepository :-
public class MainActivityRepository {
    private MutableLiveData<List<PhotoResponse>> mutableLiveData = new MutableLiveData<>();
    private static MainActivityRepository repository;

    public static MainActivityRepository getInstance() {
        if (repository == null) {
            repository = new MainActivityRepository();
        }
        return repository;
    }

    public MutableLiveData<List<PhotoResponse>> getPhotoAPI() {
        Observable<List<PhotoResponse>> observable = NetworkManager.getRetrofitServices().getPhotos("photos");
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<PhotoResponse>>() {
                    @Override                    public void onCompleted() {

                    }

                    @Override                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override                    public void onNext(List<PhotoResponse> photoResponses) {
                        mutableLiveData.setValue(photoResponses);
                    }
                });
        return mutableLiveData;
    }
}
6. MainActivityViewModel :-
public class MainActivityViewModel extends ViewModel {
    private MutableLiveData<List<PhotoResponse>> mutableLiveData;

    public void init() {
        if (mutableLiveData != null)
            return;
        else            mutableLiveData = MainActivityRepository.getInstance().getPhotoAPI();
    }

    public LiveData<List<PhotoResponse>> getDataFromRepo() {
        return mutableLiveData;
    }
}
7. MyAdapter:-
Glide
        .with(context)
        .load(responseList.get(i).getThumbnailUrl())
        .centerCrop()
        .placeholder(R.drawable.ic_launcher_background)
        .into(myViewHolderClass.imageView);

8. MainActivity:-
Important thing:-
If we are showing data or calling api on any button click and after getting data if
we rotate the screen than we will lost the data to overcome this problem we have
to do slightly changes in the code like below:-

No comments:

Post a Comment