1 /*
2  * Copyright (C) 2022 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 
17 package com.android.quicksearchbox.util
18 
19 import android.os.Handler
20 
21 /** Consumer utilities. */
22 object Consumers {
23   @JvmStatic
consumeCloseablenull24   fun <A : QuietlyCloseable?> consumeCloseable(consumer: Consumer<A>?, value: A?) {
25     var accepted = false
26     try {
27       accepted = consumer!!.consume(value!!)
28     } finally {
29       if (!accepted && value != null) value.close()
30     }
31   }
32 
33   @JvmStatic
consumeAsyncnull34   fun <A> consumeAsync(handler: Handler?, consumer: Consumer<A?>?, value: A?) {
35     if (handler == null) {
36       consumer?.consume(value)
37     } else {
38       handler.post(
39         object : Runnable {
40           override fun run() {
41             consumer?.consume(value)
42           }
43         }
44       )
45     }
46   }
47 
48   @JvmStatic
consumeCloseableAsyncnull49   fun <A : QuietlyCloseable?> consumeCloseableAsync(
50     handler: Handler?,
51     consumer: Consumer<A>?,
52     value: A?
53   ) {
54     if (handler == null) {
55       consumeCloseable(consumer, value)
56     } else {
57       handler.post(
58         object : Runnable {
59           override fun run() {
60             consumeCloseable(consumer, value)
61           }
62         }
63       )
64     }
65   }
66 
createAsyncConsumernull67   fun <A> createAsyncConsumer(handler: Handler?, consumer: Consumer<A?>?): Consumer<A?> {
68     return object : Consumer<A?> {
69       override fun consume(value: A?): Boolean {
70         consumeAsync(handler, consumer, value)
71         return true
72       }
73     }
74   }
75 
createAsyncCloseableConsumernull76   fun <A : QuietlyCloseable?> createAsyncCloseableConsumer(
77     handler: Handler?,
78     consumer: Consumer<A>?
79   ): Consumer<A?> {
80     return object : Consumer<A?> {
81       override fun consume(value: A?): Boolean {
82         consumeCloseableAsync(handler, consumer, value)
83         return true
84       }
85     }
86   }
87 }
88