AdvertisementViewModel.java
2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.polysoft.nafmii.viewmodel;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import com.polysoft.nafmii.constants.ServerApi;
import com.polysoft.nafmii.database.ObjectBox;
import com.polysoft.nafmii.database.entity.DataEntity;
import com.polysoft.nafmii.enums.StateEnum;
import com.polysoft.nafmii.net.RequestBack;
import com.polysoft.nafmii.utils.TimerUtils;
import com.whaty.nafmii.BuildConfig;
public class AdvertisementViewModel extends ViewModel {
private final MutableLiveData<LiveData> dataModel = new MutableLiveData<>();
private final LifecycleOwner owner;
private final String DB_KEY = "advertisement";
private boolean isSetModelValue = false;
public static AdvertisementViewModel newInstance(FragmentActivity owner) {
ViewModelProvider.Factory factory = new ViewModelProvider.Factory() {
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new AdvertisementViewModel(owner);
}
};
return new ViewModelProvider(owner, factory).get(AdvertisementViewModel.class);
}
AdvertisementViewModel(LifecycleOwner owner) {
this.owner = owner;
this.fetchData();
}
public void observe(Observer<LiveData> observer) {
this.dataModel.observe(this.owner, observer);
}
private void fetchData() {
TimerUtils.setTimeout(() -> {
DataEntity entity = ObjectBox.findByName(DB_KEY);
this.postModelValue(null == entity ? null : entity.getValue());
}, 2000);
ServerApi.postAdvertisement(new RequestBack<String>() {
@Override
protected void onResponse(StateEnum state, String data, String message) {
if (state.state == StateEnum.OK.state) {
postModelValue(data);
ObjectBox.put(new DataEntity(DB_KEY, data));
} else {
postModelValue(null);
}
}
});
}
private synchronized void postModelValue(String value) {
if (!this.isSetModelValue) {
this.isSetModelValue = true;
this.dataModel.postValue(new LiveData(value));
}
}
public static class LiveData {
public final String data;
LiveData(String data) {
this.data = data;
}
public boolean empty() {
if (BuildConfig.DEBUG) {
return true;
}
return TextUtils.isEmpty(data);
}
}
}