1 /*
2  * Copyright (C) 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 package android.car.cluster;
17 
18 import android.os.Handler;
19 import android.os.Looper;
20 
21 import androidx.lifecycle.LiveData;
22 
23 /**
24  * Emits a true value in a fixed periodical pace. The first beat begins when this live data becomes
25  * active.
26  *
27  * <p> Note that if this heart beat is shared, the time can be less than the given interval between
28  * observation and first beat for the second observer.
29  */
30 public class HeartBeatLiveData extends LiveData<Boolean> {
31     private long mPulseRate;
32     private Handler mMainThreadHandler = new Handler(Looper.getMainLooper());
33 
HeartBeatLiveData(long rateInMillis)34     public HeartBeatLiveData(long rateInMillis) {
35         mPulseRate = rateInMillis;
36     }
37 
38     @Override
onActive()39     protected void onActive() {
40         super.onActive();
41         mMainThreadHandler.post(mUpdateDurationRunnable);
42     }
43 
44     @Override
onInactive()45     protected void onInactive() {
46         super.onInactive();
47         mMainThreadHandler.removeCallbacks(mUpdateDurationRunnable);
48     }
49 
50     private final Runnable mUpdateDurationRunnable = new Runnable() {
51         @Override
52         public void run() {
53             setValue(true);
54             mMainThreadHandler.postDelayed(this, mPulseRate);
55         }
56     };
57 }
58