1 /*
2  * Copyright (C) 2020 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.dialer.ui.common;
18 
19 import androidx.annotation.MainThread;
20 import androidx.annotation.NonNull;
21 import androidx.annotation.Nullable;
22 import androidx.lifecycle.LifecycleOwner;
23 import androidx.lifecycle.MediatorLiveData;
24 import androidx.lifecycle.Observer;
25 
26 import java.util.concurrent.atomic.AtomicBoolean;
27 
28 /**
29  * A mediator live data implementation that propagates value ONLY ONCE.
30  */
31 public class SingleLiveEvent<T> extends MediatorLiveData<T> {
32 
33     private final AtomicBoolean mPendingUpdate = new AtomicBoolean(false);
34 
35     @Override
36     @MainThread
observe(@onNull LifecycleOwner owner, @NonNull Observer<? super T> observer)37     public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
38         super.observe(owner, value -> {
39             if (mPendingUpdate.compareAndSet(true, false)) {
40                 observer.onChanged(value);
41             }
42         });
43     }
44 
45     @Override
46     @MainThread
setValue(@ullable T value)47     public void setValue(@Nullable T value) {
48         if (value != null) {
49             mPendingUpdate.set(true);
50             super.setValue(value);
51         }
52     }
53 }
54