How to get selected items from a SWT Table using RxJava? - events

I have a table and a button and I want to emit an event ItemsSelected with the selected items of the table when the button is clicked.
The button should not know the table and it should remain only as a stream of clicks.
So this solution is discarded:
final ETable table = ...
PublishSubject<ItemSelected> selected = PublishSubject.create();
button.addSelectionListener(new SelectionListener(){
#Override
public void widgetSelected(SelectionEvent e) {
for (TableItem item : table.getSelection()) {
selected.onNext(new ItemSelected(item));
}
}
});
I would prefer a way to compose the click stream of the button with the item selection stream of the table in order to keep loose coupling between this two elements.
Because the table allows multiple selection I must first scan the items selected in order to emit an event with all the items. Something like:
public static class ItemsSelected<T> {
final List<T> items = new ArrayList<T>();
}
public abstract static class ItemSelection<T> {
public abstract void apply(ItemsSelected<T> selection);
}
public static class ItemUnselected<T> extends ItemSelection<T> {
final T item;
public ItemUnselected(T item) {
this.item = item;
}
public void apply(ItemsSelected<T> selection) {
selection.items.remove(item);
}
}
public static class ItemSelected<T> extends ItemSelection<T> {
final T item;
public ItemSelected(T item) {
this.item = item;
}
public void apply(ItemsSelected<T> selection) {
selection.items.add(item);
}
}
public static class ObservableTable<T> extends Table {
private PublishSubject<ItemSelection<T>> clicks = PublishSubject.create();
public Observable<ItemsSelected<T>> selection = clicks.scan(new ItemsSelected<T>(),
new Func2<ItemsSelected<T>, ItemSelection<T>, ItemsSelected<T>>() {
#Override
public ItemsSelected<T> call(ItemsSelected<T> t1, ItemSelection<T> t2) {
// breaking events immutability
t2.apply(t1);
return t1;
}
});
public ObservableTable(Composite parent, int style) {
super(parent, style);
this.addSelectionListener(new SelectionListener() {
#SuppressWarnings("unchecked")
#Override
public void widgetSelected(SelectionEvent e) {
if (((TableItem) e.item).getChecked())
clicks.onNext(new ItemSelected<T>((T) e.item.getData()));
else
clicks.onNext(new ItemUnselected<T>((T) e.item.getData()));
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
}
Then, I must combine the table.selection stream with the button.clicks stream in a selectionForAction stream. The idea is that when a ButtonClick is emitted, an SelectionForAction will be emitted if and only if an ItemSelected was previously emitted.
-------S1--U1-----S2---S3--------- table.clicks
(scan)
-------(1)--()---(2)---(2,3)------ table.selection
----O----------O-------------O---- button.clicks
(?)
-----------------------------(2,3) selectionForAction
So, wich operation should I use?
Zip: It doesn't work because if I click the button and later select an item, it should not do nothing, but with zip it will emit an event.
Join: I end up with a "solution" using join but it doesn't seem to be a good one. Somethinkg like:
table.selection.join(button.clicks, new Func1<ItemsSelected,Observable<Long>>() {
#Override
public Observable<Long> call(ItemsSelected t) {
// it doesn't seem a good idea
return Observable.timer(1, TimeUnit.DAYS);
}
}, new Func1<ClickEvent, Observable<Long>>() {
#Override
public Observable<Long> call(ClickEvent t) {
// this makes the ClickEvent be dropped if there is no previous ItemsSelected event emitted
return Observable.timer(1, TimeUnit.MILLISECONDS);
}
}, new Func2<ItemsSelected, ClickEvent, SelectionForAction>() {
#Override
public SelectionForActioncall(ItemsSelected t1, ClickEvent t2) {
return new SelectionForAction(t1.items);
}
});
Any idea?

I've found the operator that I needed to achieve the join behaviour with a very large time unit (DAYS in the example) and a very small one (MILLISECONDS).
With a variant of sample that takes another Observable as the sampler I could emit an event A only after an event of B would be emitted.
In my example the click acts as the sampler and the stream selection emits the events that I'm interested in. (This also requires to ignore the last event that is being emitted when the stream completes).
Another possible solution will be use the buffer(boundary):
The clicks stream would act as the boundary and I could avoid the scan operator because the list of items selected is created by the buffer operator. However with this solution I would not be considering unselection.
So, with sample I've achieved my original goal, however, I'm not happy with the way I handle items unselection and the final list of items selected.
In this case I need to maintain the state of the items selected in order to perform some operation on all of them when a ClickEvent occurs.
I could subscribe to the items selection/unselection and maintain a List of the items selected but then I'll have lost the possibility of compose the clicks observable with the selection observable.
With scan I maintain state and also keep the composability of observables, but representing the list of current selection as an event seems a little forced, in fact this represents a new issue: if I select x items and then click the button, an event with the selection is being emitted as expected, but if neither the items are unselected nor a new one is selected and then click again the button, nothing happens. So, it seems that selection doesn't fit as an event.

Related

RxJava subscription does not unsubscribe correctly

I have an MVC application in which I have to update the view with the current value of a stream.
In the model I have this method:
public Observable<Integer> getStreamInstance(){
if(stream == null){
this.stream = Observable.create((Subscriber<? super Integer> subscriber) -> {
new HeartbeatStream(frequence,subscriber).start();
});
}
return stream;
}
which I use in the controller to get the stream. Then, in the controller I have these two methods:
public void start(){
this.sb = stream.subscribe((Integer v) -> {
view.updateCurrValue(v);
});
}
public void stop(){
this.sb.unsubscribe();
}
With the start method I simply update a label in the view with the current value.
This works fine until I try to stop the updating with the unsubscribing; infact, when I press the button "stop" in the view, the label keeps updating with the current value and, if I press "start" again, the label shows the values from two different streams, the one that I first created with the first "start" and the second that seems has been created with the second pressing of "start".
Where am I wrong?
EDIT:
public class HeartbeatStream extends Thread{
private Subscriber<? super Integer> subscriber;
private int frequence;
private HeartbeatSensor sensor;
public HeartbeatStream(int freq, Subscriber<? super Integer> subscriber){
this.frequence = freq;
this.subscriber = subscriber;
sensor = new HeartbeatSensor();
}
public void run(){
while(true){
try {
subscriber.onNext(sensor.getCurrentValue());
Thread.sleep(frequence);
} catch (Exception e) {
subscriber.onError(e);
}
}
}
This is the HeartbeatStream class. HeartbeatSensor is a class that periodically generates a value that simulates the heartbeat frequence.
I'm guessing you tried to periodically signal some event that triggers the screen update. There is an operator for that:
Observable<Long> timer = Observable.interval(period, TimeUnit.MILLISECONDS,
AndroidSchedulers.mainThread());
SerialSubscription serial = new SerialSubscription();
public void start() {
serial.set(timer.subscribe(v -> view.updateCurrValue(v)));
}
public void stop() {
serial.set(Subscriptions.unsubscribed());
}
public void onDestroy() {
serial.unsubscribe();
}
Observable by design unsubscribe your observer once that all items are emitted and onComplete callback is invoked.
Look this example https://github.com/politrons/reactive/blob/master/src/test/java/rx/observables/creating/ObservableSubscription.java
I guess you're not handling the unsubscribe - although I can't see what's going on in your HeartbeatStream class.
If you're creating an Observable with Observable.create then you need to handle unsubscribing explicitly with subscriber.isUnsubscribed().
Where possible use some of the utility methods to create an Observable - they handle this all for you eg Observable.just() or Observable.from().
If this doesn't help, please post your HeartbeatStream class.
See the the docs for more details:
https://github.com/ReactiveX/RxJava/wiki/Creating-Observables
https://github.com/ReactiveX/RxJava/wiki/Async-Operators

stop click propagation of custom cell in CellTable

I've a CellTable to which I attach a click handler(via addDomHandler). Then I've added a custom cell which handles onBrowserEvent(...).
I'd like to stop the event to propagate in the cell's onBrowserEvent so that the table handler is not invoked anymore. Is this possible?
table = new CellTable();
table.addDomHandler(new ClickHandler() {
#Override
public void onClick(final ClickEvent pEvent) {
Trace.info("this shouldn't trigger");
}
}, ClickEvent.getType());
table.addColumn(new IdentityColumn<MyVO>(new MyCell()));
class MyCell extends AbstractCell<MyVO> {
#Override
public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context pContext, Element pParent,
Handle<DnSuggestionDetailsVO> pValue, NativeEvent pEvent,
ValueUpdater<Handle<DnSuggestionDetailsVO>> pValueUpdater) {
Trace.info("cell onBrowserEvent handled, propagation should stop here!");
pEvent.stopPropagation();
}
}
Thank you!
It's easier to cancel an event before it reaches the cell:
table.addCellPreviewHandler(new Handler<Item>() {
#Override
public void onCellPreview(CellPreviewEvent<Item> event) {
//do something
event.setCancelled(true);
}
});
Note that CellPreviewHandler already monitors all events within a table. You can use it for your ClickEvent as well (with finer control like which column is clicked) instead of adding a ClickHandler to the entire table.

Using DataView as a dynamic search result table in Wicket 1.4

I'm fairly new to Wicket but I've already run into a very strange problem.
I'm creating a page with a pretty basic search form and a results table (a DataView) which is initially empty. When the user enters data into the fields and clicks "Search", the app calls some backend services which are then used to populate the DataView.
However the user has to click "Search" twice for the data to be displayed.
I finally tracked this down, and it's because Wicket is using zero for the number of items to be displayed for the first "Search" click. At the second click, the rows have already been added and Wicket has already calculated the proper number of rows to display, so it decides it will show the data.
In AbstractPageableView.getItemModels(), the size of the results to display is initially zero, because I don't load the table with any initial data probably.
I got around this problem by loading the DataView with empty rows on page load. This seems to trick the DataView into using the displaying the data for the first "Search" click.
My question is: am I doing this right? Is there another repeater that is better for this task? Is this a bug or something?
Finally cracked it: it was because I was loading the data in my data provider only in the iterator() method, and the data provider's size() method is usually called before the iterator() method is. I should have been loading the data in its own method and calling that method from iterator() and size(). Doing that fixed it.
Data Provider before (Splc is the DTO):
SearchResultsDataProvider implements IDataProvider<Splc> {
/**
* The list of search results
*/
private List<Splc> models;
#Override
public void detach() {
// Do nothing
}
#Override
public Iterator<Splc> iterator(int first, int count) {
// load the data into the list of models
models = service.getSplcModels();
return models.subList(....).iterator();
}
#Override
public IModel<Splc> model(Splc object) {
return new Model<Splc>(object);
}
#Override
public int size() {
return models.size();
}
}
Data Provider after:
SearchResultsDataProvider implements IDataProvider<Splc> {
private List<Splc> getModels() {
// load the data into the list of models
return service.getSplcModels();
}
#Override
public void detach() {
// Do nothing
}
#Override
public Iterator<Splc> iterator(int first, int count) {
return getModels().subList(....).iterator();
}
#Override
public IModel<Splc> model(Splc object) {
return new Model<Splc>(object);
}
#Override
public int size() {
return getModels().size();
}
}

wicket - Implement Ajax add/remove items ListView

Im getting crazy about this issue. I implemented a ListView which you can add/remove TextField dinamically, but only the last TextField is removed.
An example:
// Object type which is used in the list
public class ExampleObject implements Serializable{
private String keyword;
public String getKeyword() {
return this.keyword;
}
public void setKeyword(String s) {
keyword = s;
}
}
//ListView
List<ExampleObject> keywordList = new ArrayList<ExampleObject>();
keywordList.add(new ExampleObject());
ListView keywordView = new ListView("keywordView", keywordList) {
#Override
protected void populateItem(final ListItem item) {
ExampleObject model = (ExampleObject) item.getModelObject();
item.add(new TextField("subKeyword", new PropertyModel(model, "keyword")));
// keyword remove link
AjaxSubmitLink removeKeyword = new AjaxSubmitLink("removeKeyword", myForm)
{
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
ExampleObject selected = (ExampleObject) item.getModelObject();
// I also tried deleting by index. println shows the
// selected object is the element I want to remove, so why always
// remove last object of the list?
keywordList.remove(selected);
if (target != null) {
target.addComponent(myForm);
}
}
};
item.add(removeKeyword);
// keyword add link
AjaxSubmitLink addKeyword = new AjaxSubmitLink("addKeyword", metadataForm)
{
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
keywordList.add(new ExampleObject());
if (target != null) {
target.addComponent(myForm);
}
}
};
item.add(addKeyword);
}
keywordView.setReuseItems(true);
metadataForm.add(keywordView);
Any help would be very appreciate, because I thing this issue is really a very stupid mistake but I cant get it!
Thanks
It might be as simple as getting rid of the line
keywordView.setReuseItems(true);
The reuseItems flag is an efficiency so that the page does not rebuild the ListView items unnecessarily, but it can lead to confusion such as what you're seeing.
ListView really wasn't made for use with forms though, and you'll probably be better off with another tactic entirely.
This blog entry on building a list editor form component might be useful. It will need some changes if you're not on Wicket 1.4, but similar stuff is definitely possible in Wicket 1.3, and the comments have some hints.
Read the javadoc of ListView#setReuseItems():
"But if you modify the listView model object, than you must manually call listView.removeAll() in order to rebuild the ListItems."
You can not use a ListView this way. Either use the members of ListView provided:
removeLink(java.lang.String id, ListItem<T> item)
and
newItem(int index)
but, I never used those. If I have to display a List and be able to add remove Items dynamically, I prefer the RefreshingView.
If you do use FormComponents inside a RefreshingView, make sure you set a Reusestartegy (setItemReuseStrategy())
Bert

BlackBerry - Add items to a ListField

Can someone please give me a simple example on how to add three rows to a ListField so that the list shows something like this?
Item 1
Item 2
Item 3
I just want to show a list in which the user can select one of the items and the program would do something depending on the item selected.
I've search all over the internet but it seems impossible to find a simple example on how to do this (most examples I found are incomplete) and the blackberry documentation is terrible.
Thanks!
You probably want to look at using an ObjectListField. Handling the select action is done throught the containing Screen object, I've done this below using a MenuItem, I'm not really sure how to set a default select listener, you may have to detect key and trackwheel events.
Some example code for you: (not tested!)
MainScreen screen = new MainScreen();
screen.setTitle("my test");
final ObjectListField list = new ObjectLIstField();
String[] items = new String[] { "Item 1", "Item 2", "Item 3" };
list.set(items);
screen.addMenuItem(new MenuItem("Select", 100, 1) {
public void run() {
int selectedIndex = list.getSelectedIndex();
String item = (String)list.get(selectedIndex);
// Do someting with item
});
screen.add(list);
You can override the navigationClick method like this:
ObjectListField list = new ObjectListField()
{
protected boolean navigationClick(int status, int time)
{
// Your implementation here.
}
};
final class SimpleListScreen extends MainScreen
{
public SimpleListScreen()
{
super(Manager.NO_VERTICAL_SCROLL);
setTitle("Simple List Demo");
add(new LabelField("My list", LabelField.FIELD_HCENTER));
add(new SeparatorField());
Manager mainManager = getMainManager();
SimpleList listField = new SimpleList(mainManager);
listField.add("Item 1");
listField.add("Item 2");
listField.add("Item 3");
}
}
//add listener so that when an item is chosen,it will do something
private ListField fList = new ListField(){
protected boolean navigationClick(int status, int time) {
System.out.println("omt Click");
return true;
};
};
You can detect the click on each list item by overriding
protected boolean navigationClick(int status,int time)
Then you just need to work out what to do in response to the click. The way I did this was by using an anonymous class, set for each list item.

Resources