• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018 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.car.arch.common.switching;
18 
19 import androidx.annotation.NonNull;
20 import androidx.annotation.Nullable;
21 import androidx.lifecycle.LiveData;
22 import androidx.lifecycle.MediatorLiveData;
23 
24 /**
25  * Provides the implementation of {@link SwitchingLiveData}. This class uses an interface rather
26  * than being exposed directly to ensure that its superclass {@link MediatorLiveData} is not
27  * exposed. The use of MediatorLiveData is an implementation detail.
28  */
29 class SwitchingLiveDataImpl<T> extends MediatorLiveData<T> implements SwitchingLiveData<T> {
30     private LiveData<? extends T> mCurrentSource;
31 
32     @NonNull
33     @Override
asLiveData()34     public LiveData<T> asLiveData() {
35         return this;
36     }
37 
38     @Nullable
39     @Override
getSource()40     public LiveData<? extends T> getSource() {
41         return mCurrentSource;
42     }
43 
setSource(@ullable LiveData<? extends T> source)44     public void setSource(@Nullable LiveData<? extends T> source) {
45         if (source == mCurrentSource) {
46             return;
47         }
48         if (mCurrentSource != null) {
49             removeSource(mCurrentSource);
50         }
51         mCurrentSource = source;
52         if (source != null) {
53             addSource(source, this::setValue);
54         } else {
55             setValue(null);
56         }
57     }
58 }
59