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 18 package com.android.systemui.user.domain.interactor 19 20 import com.android.systemui.dagger.SysUISingleton 21 import com.android.systemui.dagger.qualifiers.Application 22 import com.android.systemui.dagger.qualifiers.Main 23 import com.android.systemui.user.data.repository.UserRepository 24 import javax.inject.Inject 25 import kotlinx.coroutines.CoroutineDispatcher 26 import kotlinx.coroutines.CoroutineScope 27 import kotlinx.coroutines.Job 28 import kotlinx.coroutines.delay 29 import kotlinx.coroutines.launch 30 31 /** Encapsulates logic for pausing, unpausing, and scheduling a delayed job. */ 32 @SysUISingleton 33 class RefreshUsersScheduler 34 @Inject 35 constructor( 36 @Application private val applicationScope: CoroutineScope, 37 @Main private val mainDispatcher: CoroutineDispatcher, 38 private val repository: UserRepository, 39 ) { 40 private var scheduledUnpauseJob: Job? = null 41 private var isPaused = false 42 pausenull43 fun pause() { 44 applicationScope.launch(mainDispatcher) { 45 isPaused = true 46 scheduledUnpauseJob?.cancel() 47 scheduledUnpauseJob = 48 applicationScope.launch { 49 delay(PAUSE_REFRESH_USERS_TIMEOUT_MS) 50 unpauseAndRefresh() 51 } 52 } 53 } 54 unpauseAndRefreshnull55 fun unpauseAndRefresh() { 56 applicationScope.launch(mainDispatcher) { 57 isPaused = false 58 refreshIfNotPaused() 59 } 60 } 61 refreshIfNotPausednull62 fun refreshIfNotPaused() { 63 applicationScope.launch(mainDispatcher) { 64 if (isPaused) { 65 return@launch 66 } 67 68 repository.refreshUsers() 69 } 70 } 71 72 companion object { 73 private const val PAUSE_REFRESH_USERS_TIMEOUT_MS = 3000L 74 } 75 } 76