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