1 /* 2 * 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.systemui.slice 18 19 import android.net.Uri 20 import androidx.slice.Slice 21 import androidx.slice.SliceViewManager 22 import com.android.systemui.common.coroutine.ConflatedCallbackFlow 23 import kotlinx.coroutines.channels.awaitClose 24 import kotlinx.coroutines.flow.Flow 25 import kotlinx.coroutines.launch 26 27 /** 28 * Returns updating [Slice] for a [sliceUri]. It's null when there is no slice available for the 29 * provided Uri. This can change overtime because of external changes (like device being 30 * connected/disconnected). 31 * 32 * The flow should be [kotlinx.coroutines.flow.flowOn] the main thread because [SliceViewManager] 33 * isn't thread-safe. An exception will be thrown otherwise. 34 */ sliceForUrinull35fun SliceViewManager.sliceForUri(sliceUri: Uri): Flow<Slice?> = 36 ConflatedCallbackFlow.conflatedCallbackFlow { 37 val callback = SliceViewManager.SliceCallback { launch { send(it) } } 38 39 val slice = bindSlice(sliceUri) 40 send(slice) 41 registerSliceCallback(sliceUri, callback) 42 awaitClose { unregisterSliceCallback(sliceUri, callback) } 43 } 44