Skip to content

Instantly share code, notes, and snippets.

@kwong93
Last active September 15, 2017 16:10
Show Gist options
  • Save kwong93/1b3c8f96be2bcc40e14fb81df37e0024 to your computer and use it in GitHub Desktop.
Save kwong93/1b3c8f96be2bcc40e14fb81df37e0024 to your computer and use it in GitHub Desktop.
How to use new ViewModel library
/**
* The view model class
*/
public class TestViewModel extends AndroidViewModel {
private final StocksLiveData stocksLiveData;
public TestViewModel(Application application) {
super(application);
stocksLiveData = new StocksLiveData(application);
}
public LiveData<ResourceModel<List<StockModel>>> getStocks(String category, boolean refresh) {
if (stocksLiveData.getValue() == null) {
stocksLiveData.load(category);
} else {
if (refresh && !stocksLiveData.getValue().status.equals(ResourceModel.Status.LOADING)) {
stocksLiveData.load(category);
}
}
return stocksLiveData;
}
public class StocksLiveData extends LiveData<ResourceModel<List<StockModel>>> {
private final Context context;
public StocksLiveData(Context context) {
this.context = context;
}
@Override
protected void onActive() {
}
@Override
protected void onInactive() {
}
public void load(final String category) {
setValue(ResourceModel.<List<StockModel>>loading(null));
Single<List<StockModel>> single = Single.fromCallable(new Callable<List<StockModel>>() {
@Override
public List<StockModel> call() throws Exception {
String json = getJson("https://api.iextrading.com/1.0/tops/" + category);
if (json != null) {
Gson gson = new Gson();
Type typeOf = new TypeToken<List<StockModel>>() {
}.getType();
Thread.sleep(10000);
return gson.fromJson(json, typeOf);
}
return new ArrayList<>();
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
single.subscribeWith(new DisposableSingleObserver<List<StockModel>>() {
@Override
public void onSuccess(@NonNull List<StockModel> stockModels) {
setValue(ResourceModel.success(stockModels));
}
@Override
public void onError(@NonNull Throwable e) {
setValue(ResourceModel.<List<StockModel>>error("", null));
}
});
}
}
public String getJson(String endpoint) throws Exception {
HttpURLConnection httpURLConnection;
URL url = new URL(endpoint);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == 200) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) {
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
}
}
return null;
}
}
/**
* The activity class
* NOTE: LifecycleActivity is a temporary implementation detail until Lifecycles are integrated with support
* library. You should use AppCompatActivity once it is implemented.
* EDIT: As of support revision 26.1.0 you can use AppCompatActivity
*/
public class ViewModelTestActivity extends LifecycleActivity {
private TestViewModel viewModel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vm);
viewModel = ViewModelProviders.of(this).get(TestViewModel.class);
LiveData<ResourceModel<List<StockModel>>> liveData = viewModel.getStocks("last", false);
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewModel.getStocks("last", true);
}
});
liveData.observe(this, new Observer<ResourceModel<List<StockModel>>>() {
@Override
public void onChanged(@Nullable ResourceModel<List<StockModel>> resourceModel) {
if (resourceModel != null) {
if (resourceModel.status.equals(ResourceModel.Status.LOADING)) {
findViewById(R.id.progress).setVisibility(View.VISIBLE);
} else if (resourceModel.status.equals(ResourceModel.Status.ERROR)) {
findViewById(R.id.progress).setVisibility(View.GONE);
} else if (resourceModel.status.equals(ResourceModel.Status.SUCCESS)) {
findViewById(R.id.progress).setVisibility(View.GONE);
TextView textView = (TextView) findViewById(R.id.text);
textView.setText(String.valueOf(resourceModel.data.size()));
}
}
}
});
}
}
/**
* The model classes
*/
public class ResourceModel<T> {
public enum Status {
SUCCESS,
ERROR,
LOADING
}
public final Status status;
public final String message;
public final T data;
public ResourceModel(Status status, T data, String message) {
this.status = status;
this.data = data;
this.message = message;
}
public static <T> ResourceModel<T> success(T data) {
return new ResourceModel<>(Status.SUCCESS, data, null);
}
public static <T> ResourceModel<T> error(String msg, T data) {
return new ResourceModel<>(Status.ERROR, data, msg);
}
public static <T> ResourceModel<T> loading(T data) {
return new ResourceModel<>(Status.LOADING, data, null);
}
}
public class StockModel {
public String symbol;
public double price;
public int size;
public long time;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment