Added Android code
[wl-app.git] / Android / app / src / main / java / com / moiseum / wolnelektury / base / DataProvider.java
1 package com.moiseum.wolnelektury.base;
2
3 import android.util.Log;
4
5 import com.moiseum.wolnelektury.connection.RestClientCallback;
6
7 import javax.annotation.Nullable;
8
9 import retrofit2.Call;
10
11 /**
12  * @author golonkos.
13  */
14
15 public abstract class DataProvider<T, S> extends RestClientCallback<T, S> {
16
17         private final static String TAG = DataProvider.class.getSimpleName();
18
19         protected DataObserver<T> dataObserver;
20         protected String lastKeySlug = null;
21         private Call<T> call;
22
23         public DataProvider() {
24         }
25
26         public void setDataObserver(DataObserver<T> dataObserver) {
27                 this.dataObserver = dataObserver;
28         }
29
30         @Override
31         public void onSuccess(T data) {
32                 if (dataObserver != null) {
33                         dataObserver.onLoadSuccess(data);
34                 }
35         }
36
37         @Override
38         public void onFailure(Exception e) {
39                 Log.e(TAG, "Failed to load data", e);
40                 if (dataObserver != null) {
41                         dataObserver.onLoadFailed(e);
42                 }
43         }
44
45         @Override
46         public void onCancel() {
47                 //nop
48         }
49
50         /**
51          * Invoked in order to load data.
52          * @param lastKey Last book slug for pagination. Can be null if there is no pagination.
53          */
54         public void load(@Nullable String lastKey) {
55                 cancel();
56                 lastKeySlug = lastKey;
57                 call = WLApplication.getInstance().getRestClient().call(this, getServiceClass());
58                 if (dataObserver != null) {
59                         dataObserver.onLoadStarted();
60                 }
61         }
62
63         public void cancel() {
64                 if (call != null) {
65                         call.cancel();
66                         call = null;
67                 }
68         }
69
70         public void release() {
71                 dataObserver = null;
72         }
73
74         protected abstract Class<S> getServiceClass();
75 }