View Javadoc
1   package au.gov.amsa.geo.distance;
2   
3   import java.util.ArrayList;
4   import java.util.LinkedList;
5   import java.util.List;
6   
7   import org.apache.log4j.Logger;
8   
9   import rx.Observable.Operator;
10  import rx.Observer;
11  import rx.Subscriber;
12  import rx.observers.Subscribers;
13  
14  /**
15   * Presizes the ArrayList returned by the given size parameter. This will save
16   * some seconds in run time for large lists.
17   */
18  public class OperatorToObservableSizedList<T> implements Operator<List<T>, T> {
19  
20  	private static Logger log = Logger
21  			.getLogger(OperatorToObservableSizedList.class);
22  
23  	private final int size;
24  
25  	public OperatorToObservableSizedList(int size) {
26  		this.size = size;
27  	}
28  
29  	@Override
30  	public Subscriber<? super T> call(final Subscriber<? super List<T>> child) {
31  		log.info("allocating list of size " + size);
32  		final List<T> list;
33  		if (size == 0)
34  			list = new LinkedList<T>();
35  		else
36  			list = new ArrayList<T>(size);
37  		log.info("allocated");
38  		Subscriber<T> parent = Subscribers.from(new Observer<T>() {
39  
40  			@Override
41  			public void onCompleted() {
42  				child.onNext(list);
43  				child.onCompleted();
44  			}
45  
46  			@Override
47  			public void onError(Throwable e) {
48  				child.onError(e);
49  			}
50  
51  			@Override
52  			public void onNext(T t) {
53  				list.add(t);
54  			}
55  		});
56  		child.add(parent);
57  		return parent;
58  	}
59  
60  }