Line data Source code
1 : // Copyright (C) 2019 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.index.query; 16 : 17 : import static java.util.Objects.requireNonNull; 18 : 19 : import com.google.common.collect.ImmutableList; 20 : import java.util.Iterator; 21 : import java.util.function.Supplier; 22 : 23 : /** 24 : * Result set that allows for asynchronous execution of the actual query. Callers should dispatch 25 : * the query and call the constructor of this class with a supplier that fetches the result and 26 : * blocks on it if necessary. 27 : * 28 : * <p>If the execution is synchronous or the results are known a priori, consider using {@link 29 : * ListResultSet}. 30 : */ 31 : public class LazyResultSet<T> implements ResultSet<T> { 32 : private final Supplier<ImmutableList<T>> resultsCallback; 33 : 34 121 : private boolean resultsReturned = false; 35 : 36 121 : public LazyResultSet(Supplier<ImmutableList<T>> r) { 37 121 : resultsCallback = requireNonNull(r, "results can't be null"); 38 121 : } 39 : 40 : @Override 41 : public Iterator<T> iterator() { 42 0 : return toList().iterator(); 43 : } 44 : 45 : @Override 46 : public ImmutableList<T> toList() { 47 121 : if (resultsReturned) { 48 0 : throw new IllegalStateException("Results already obtained"); 49 : } 50 121 : resultsReturned = true; 51 120 : return resultsCallback.get(); 52 : } 53 : 54 : @Override 55 0 : public void close() {} 56 : 57 : @Override 58 : public Object searchAfter() { 59 0 : return null; 60 : } 61 : }