Home | History | Annotate | Download | only in intentplayground
      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 
     17 package com.example.android.intentplayground;
     18 
     19 import androidx.lifecycle.LiveData;
     20 import androidx.lifecycle.MutableLiveData;
     21 import androidx.lifecycle.ViewModel;
     22 
     23 import java.util.List;
     24 import java.util.function.Consumer;
     25 
     26 public class BaseActivityViewModel extends ViewModel {
     27     enum FabAction {Show, Hide}
     28 
     29     private final MutableLiveData<FabAction> mFabActions;
     30 
     31     /**
     32      * Republish {@link BaseActivity#addTrackerListener(Consumer)} in a lifecycle safe manner.
     33      * The {@link BaseActivity#addTrackerListener(Consumer)} that is registered in this class,
     34      * forwards the value to this, to enjoy all the guarantees {@link import
     35      * androidx.lifecycle.LiveData;} gives.
     36      */
     37     private final MutableLiveData<List<Tracking.Task>> mRefreshTree;
     38     private final Consumer<List<Tracking.Task>> mTrackingListener;
     39 
     40     public BaseActivityViewModel() {
     41         mFabActions = new MutableLiveData<>();
     42         mRefreshTree = new MutableLiveData<>();
     43         mTrackingListener = tasks -> mRefreshTree.setValue(tasks);
     44         BaseActivity.addTrackerListener(mTrackingListener);
     45     }
     46 
     47 
     48     public void actOnFab(FabAction action) {
     49         mFabActions.setValue(action);
     50     }
     51 
     52     public LiveData<FabAction> getFabActions() {
     53         return mFabActions;
     54     }
     55 
     56     /**
     57      * @return LiveData that publishes the new state of {@link com.android.server.wm.Task} and
     58      * {@link android.app.Activity}-s whenever that state has been changed.
     59      */
     60     public LiveData<List<Tracking.Task>> getRefresh() {
     61         return mRefreshTree;
     62     }
     63 
     64     @Override
     65     public void onCleared() {
     66         BaseActivity.removeTrackerListener(mTrackingListener);
     67     }
     68 }
     69 
     70