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.settingslib.spa.framework.common 18 19 import androidx.lifecycle.LiveData 20 import androidx.slice.Slice 21 import kotlinx.coroutines.CoroutineScope 22 import kotlinx.coroutines.Dispatchers 23 import kotlinx.coroutines.Job 24 import kotlinx.coroutines.launch 25 26 open class EntrySliceData : LiveData<Slice?>() { 27 private val asyncRunnerScope = CoroutineScope(Dispatchers.IO) 28 private var asyncRunnerJob: Job? = null 29 private var asyncActionJob: Job? = null 30 private var isActive = false 31 asyncRunnernull32 open suspend fun asyncRunner() {} 33 asyncActionnull34 open suspend fun asyncAction() {} 35 onActivenull36 override fun onActive() { 37 asyncRunnerJob?.cancel() 38 asyncRunnerJob = asyncRunnerScope.launch { asyncRunner() } 39 isActive = true 40 } 41 onInactivenull42 override fun onInactive() { 43 asyncRunnerJob?.cancel() 44 asyncRunnerJob = null 45 asyncActionJob?.cancel() 46 asyncActionJob = null 47 isActive = false 48 } 49 isActivenull50 fun isActive(): Boolean { 51 return isActive 52 } 53 doActionnull54 fun doAction() { 55 asyncActionJob?.cancel() 56 asyncActionJob = asyncRunnerScope.launch { asyncAction() } 57 } 58 } 59