Skip to content

Instantly share code, notes, and snippets.

@tsuoanttila
Created July 5, 2018 09:23
Show Gist options
  • Save tsuoanttila/370dfbadcb27346db42a03de15f85fb9 to your computer and use it in GitHub Desktop.
Save tsuoanttila/370dfbadcb27346db42a03de15f85fb9 to your computer and use it in GitHub Desktop.
Sizeless DataCommunicator for Vaadin 8
package com.example.test_app;
import java.util.List;
import com.vaadin.data.provider.DataCommunicator;
import com.vaadin.shared.Range;
import com.vaadin.shared.data.DataCommunicatorClientRpc;
import elemental.json.Json;
import elemental.json.JsonArray;
public class SizelessDataCommunicator<T> extends DataCommunicator<T> {
DataCommunicatorClientRpc rpc = getRpcProxy(
DataCommunicatorClientRpc.class);
int knownSize = 0;
@Override
protected void sendDataToClient(boolean initial) {
if (getDataProvider() == null) {
return;
}
if (initial) {
rpc.reset(0);
}
Range requestedRows = getPushRows();
if (!requestedRows.isEmpty()) {
int offset = requestedRows.getStart();
// Always fetch some extra rows.
int limit = requestedRows.length() + getMinPushSize();
List<T> rowsToPush = fetchItemsWithRange(offset, limit);
int lastIndex = offset + rowsToPush.size();
if (lastIndex > knownSize) {
int rowsToAdd = lastIndex - knownSize;
rpc.insertRows(knownSize,
rowsToAdd + (rowsToPush.size() == limit ? 1 : 0));
knownSize = lastIndex;
} else if (rowsToPush.size() < requestedRows.length()) {
// Size decreased
int rowsToRemove = Math.max(
requestedRows.length() - rowsToPush.size(),
knownSize - lastIndex);
knownSize = lastIndex;
rpc.removeRows(knownSize, rowsToRemove);
}
pushData(offset, rowsToPush);
}
if (!getUpdatedData().isEmpty()) {
JsonArray dataArray = Json.createArray();
int i = 0;
for (T data : getUpdatedData()) {
dataArray.set(i++, getDataObject(data));
}
rpc.updateData(dataArray);
}
setPushRows(Range.withLength(0, 0));
getUpdatedData().clear();
}
@Override
public int getDataProviderSize() {
return knownSize;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment