1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.quicksearchbox.util;
18
19import android.os.Handler;
20
21/**
22 * Consumer utilities.
23 */
24public class Consumers {
25
26    private Consumers() {}
27
28    public static <A extends QuietlyCloseable> void consumeCloseable(Consumer<A> consumer,
29            A value) {
30        boolean accepted = false;
31        try {
32            accepted = consumer.consume(value);
33        } finally {
34            if (!accepted && value != null) value.close();
35        }
36    }
37
38    public static <A> void consumeAsync(Handler handler,
39            final Consumer<A> consumer, final A value) {
40        if (handler == null) {
41            consumer.consume(value);
42        } else {
43            handler.post(new Runnable() {
44                public void run() {
45                    consumer.consume(value);
46                }
47            });
48        }
49    }
50
51    public static <A extends QuietlyCloseable> void consumeCloseableAsync(Handler handler,
52            final Consumer<A> consumer, final A value) {
53        if (handler == null) {
54            consumeCloseable(consumer, value);
55        } else {
56            handler.post(new Runnable() {
57                public void run() {
58                    consumeCloseable(consumer, value);
59                }
60            });
61        }
62    }
63
64    public static <A> Consumer<A> createAsyncConsumer(
65            final Handler handler, final Consumer<A> consumer) {
66        return new Consumer<A>() {
67            public boolean consume(A value) {
68                consumeAsync(handler, consumer, value);
69                return true;
70            }
71        };
72    }
73
74    public static <A extends QuietlyCloseable> Consumer<A> createAsyncCloseableConsumer(
75            final Handler handler, final Consumer<A> consumer) {
76        return new Consumer<A>() {
77            public boolean consume(A value) {
78                consumeCloseableAsync(handler, consumer, value);
79                return true;
80            }
81        };
82    }
83
84}
85