• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright (C) 2024 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.settings.fuelgauge.utils
18 
19 import androidx.lifecycle.DefaultLifecycleObserver
20 import androidx.lifecycle.Lifecycle
21 import androidx.lifecycle.LifecycleOwner
22 import java.util.concurrent.ExecutorService
23 import java.util.concurrent.Executors
24 
25 /**
26  *  The factory class to create executors which could bind with an UI page lifecycle and shutdown
27  *  automatically when onStop() method was invoked.
28  *
29  *  NOTE: Creating an executor from an UI page MUST set the lifecycle. Only non-UI jobs can set
30  *  the lifecycle to null.
31  */
32 object LifecycleAwareExecutorFactory {
33 
34     fun newSingleThreadExecutor(lifecycle: Lifecycle?): ExecutorService {
35         return Executors.newSingleThreadExecutor().also { executor ->
36             executor.autoShutdown(lifecycle)
37         }
38     }
39 
40     fun newFixedThreadPool(lifecycle: Lifecycle?, nThreads: Int): ExecutorService {
41         return Executors.newFixedThreadPool(nThreads).also { executor ->
42             executor.autoShutdown(lifecycle)
43         }
44     }
45 
46     fun newCachedThreadPool(lifecycle: Lifecycle?): ExecutorService {
47         return Executors.newCachedThreadPool().also { executor ->
48             executor.autoShutdown(lifecycle)
49         }
50     }
51 
52     private fun ExecutorService.autoShutdown(lifecycle: Lifecycle?) {
53         if (lifecycle == null) {
54             return
55         }
56 
57         val observer = object : DefaultLifecycleObserver {
58             override fun onStop(owner: LifecycleOwner) {
59                 this@autoShutdown.shutdown()
60                 owner.lifecycle.removeObserver(this)
61             }
62         }
63         lifecycle.addObserver(observer)
64     }
65 }
66