1 /* 2 * Copyright (C) 2019 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.packageinstaller.role.ui; 18 19 import android.content.pm.ApplicationInfo; 20 import android.util.Pair; 21 22 import androidx.annotation.NonNull; 23 import androidx.lifecycle.MediatorLiveData; 24 25 import java.util.ArrayList; 26 import java.util.List; 27 28 /** 29 * {@link MediatorLiveData} that merges multiple {@link RoleLiveData} instances. 30 */ 31 public class MergeRoleLiveData extends MediatorLiveData<List<Pair<ApplicationInfo, Boolean>>> { 32 33 @NonNull 34 private final RoleLiveData[] mLiveDatas; 35 MergeRoleLiveData(@onNull RoleLiveData... liveDatas)36 public MergeRoleLiveData(@NonNull RoleLiveData... liveDatas) { 37 mLiveDatas = liveDatas; 38 39 int liveDatasLength = mLiveDatas.length; 40 for (int i = 0; i < liveDatasLength; i++) { 41 RoleLiveData liveData = mLiveDatas[i]; 42 43 addSource(liveData, roleItems -> onRoleChanged()); 44 } 45 } 46 onRoleChanged()47 private void onRoleChanged() { 48 List<Pair<ApplicationInfo, Boolean>> mergedQualifyingApplications = new ArrayList<>(); 49 int liveDatasLength = mLiveDatas.length; 50 for (int i = 0; i < liveDatasLength; i++) { 51 RoleLiveData liveData = mLiveDatas[i]; 52 53 List<Pair<ApplicationInfo, Boolean>> qualifyingApplications = liveData.getValue(); 54 if (qualifyingApplications == null) { 55 return; 56 } 57 mergedQualifyingApplications.addAll(qualifyingApplications); 58 } 59 60 setValue(mergedQualifyingApplications); 61 } 62 } 63