Monday, 13 May 2019

MVVM with LiveData and Retrofit example in android | How to call or make an API call using MVVM patterns with LiveData in android example

1 > Here is the basic example of MVVM using live Data. To follow MVVM pattern make following package :-
1. model:- Pojo Class 
2. view:- All Activity ,Fragment ,Adapter will come inside, view will communicate with viewModel.
3. viewModel :- viewModel will call repository where all business logic will be there.
4. repositories :- It will communicate with wenServer or database to get the data .
5. webServices :- Retrofit class , APIServices related class will be here.

I am going to call following API using Retrofit:- 


2. > Dependencies :-


//RecyclerView
implementation 'com.android.support:recyclerview-v7:28.0.0'
// 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.ofdef 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'
3. > Now i created related all classes inside all folder :-

 AlbumResponse :- 



AlbumAdapter:-

APIServices:-

public interface APIServices {
    @GET("{albums}")
    Observable<List<AlbumResponse>> getEmpDetails(@Path("albums") String albums);
}

NetworkManager:-


public static Retrofit getRetrofitInstance() {
    if (retrofit == null) {
        retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
    }
    return retrofit;
}

MainActivityRepo:-

private MutableLiveData<List<AlbumResponse>> mutableLiveData;
private APIServices serviceAPI;

public MainActivityRepo() {
    if(mutableLiveData == null){
        mutableLiveData = new MutableLiveData<>();
    }
    serviceAPI = NetworkManager.getRetrofitInstance().create(APIServices.class);
}
//Call API
//Call APIpublic MutableLiveData<List<AlbumResponse>> getEmployeDetailAPi() {
    Observable<List<AlbumResponse>> observable = serviceAPI.getEmpDetails("albums");
    observable.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<List<AlbumResponse>>() {
                @Override                public void onCompleted() {
                }
                @Override                public void onError(Throwable e) {
                }
                @Override                public void onNext(List<AlbumResponse> albumResponses) {
                    mutableLiveData.setValue(albumResponses);
                }
            });
    return mutableLiveData;
}

MainActivityViewModel:-
public MutableLiveData<List<AlbumResponse>> getEmpDetailFromDB() {
    return activityRepo.getEmployeDetailAPi();
}

MainActivity:-
private void initRecyclerView(List<AlbumResponse> responses) {
    AlbumAdapter adapter = new AlbumAdapter(responses);
    RecyclerView.LayoutManager manager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(manager);
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
}

private void getEmpDetailFromViewModel() {
    viewModel.getEmpDetailFromDB().observe(this, new Observer<List<AlbumResponse>>() {
        @Override        public void onChanged(@Nullable List<AlbumResponse> albumResponses) {
            initRecyclerView(albumResponses);
        }
    });
}

Output:-



No comments:

Post a Comment