I am using Vaadin 23 and trying to perform a sort. However, requirement is to sort the fetched element on the UI and not invoking the backend.
Here is the code for reference
Setting up backend data provider
@Override
protected Stream<MyClassWrapper> fetchFromBackEnd(Query<MyClassWrapper, MyFilter> query) {
MyFilter initFilter = MyFilter.builder().build();
Stream<MyClass> stream = myService.getData(initFilter).stream();
Stream<MyClassWrapper> wrapperStream = stream.map(MyClassWrapper::new).sorted();
return wrapperStream;
}
Grid creation
public class MyGridComponent extends Grid<MyWrapper> {
public MyGridComponent() {
super(MyWrapper.class, false);
addColumn(MyWrapper::getName)
.setHeader("Column1")
.setSortable(true)
.setComparator(MyWrapper::getColumn1)
.setId("my-grid-column-name");
}
}
I tried a setComparator() on the column but it is invoking the API. Any lead will be appreciated.
The whole point of Backend-DataProviders is that not all of the DB items need to be loaded eagerly. But when you sort or filter the list, the sorting/filtering should apply to all of them so the service needs to be invoked.
You would have to use an in-memory dataprovider like ListDataProvider and load ALL the items from your DB/service once in the beginning. Only then will no service be invoked after sorting and filtering.
MyGridComponent grid = new MyGridComponent();
grid.setItems(myService.findAll());
// grid.setItems(..) will use a ListDataProvider<GRID_ITEM_CLASS>
// so you'd have to either wrap the item-collection here, or change the grid item class
The drawback of this approach is of course that the initial load is longer the more items you have in your DB. If the amount of items is not in the thousands, this is barely noticeable. But if you have lots and lots of items, invoking the API upon each sort is usually preferred since the api will return a small number of items each time