1 /* 2 * Copyright 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.calendar; 18 19 import android.content.ContentResolver; 20 import android.os.HandlerThread; 21 import android.util.Log; 22 23 import androidx.annotation.Nullable; 24 import androidx.lifecycle.ViewModel; 25 26 import com.android.car.calendar.common.EventDescriptions; 27 import com.android.car.calendar.common.EventLocations; 28 import com.android.car.calendar.common.EventsLiveData; 29 30 import java.time.Clock; 31 import java.util.Locale; 32 33 class CarCalendarViewModel extends ViewModel { 34 private static final String TAG = "CarCalendarViewModel"; 35 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); 36 37 private final HandlerThread mHandlerThread = new HandlerThread("CarCalendarBackground"); 38 private final Clock mClock; 39 private final ContentResolver mResolver; 40 private final Locale mLocale; 41 42 @Nullable private EventsLiveData mEventsLiveData; 43 CarCalendarViewModel(ContentResolver resolver, Locale locale, Clock clock)44 CarCalendarViewModel(ContentResolver resolver, Locale locale, Clock clock) { 45 if (DEBUG) Log.d(TAG, "Creating view model"); 46 mResolver = resolver; 47 mHandlerThread.start(); 48 mLocale = locale; 49 mClock = clock; 50 } 51 52 /** Creates an {@link EventsLiveData} lazily and always returns the same instance. */ getEventsLiveData()53 EventsLiveData getEventsLiveData() { 54 if (mEventsLiveData == null) { 55 mEventsLiveData = 56 new EventsLiveData( 57 mClock, 58 mHandlerThread.getThreadHandler(), 59 mResolver, 60 new EventDescriptions(mLocale), 61 new EventLocations()); 62 } 63 return mEventsLiveData; 64 } 65 66 @Override onCleared()67 protected void onCleared() { 68 super.onCleared(); 69 mHandlerThread.quitSafely(); 70 } 71 } 72