Skip to content

Commit

Permalink
Missing widgetmodel repo
Browse files Browse the repository at this point in the history
Change-Id: I9402e4716f6f977f8edb25faad751f4fa988749b
  • Loading branch information
secondsun committed Mar 22, 2024
1 parent 3dd55c4 commit 920a557
Showing 1 changed file with 65 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.android.samples.socialite.widget.model

import android.content.Context
import androidx.glance.appwidget.updateAll
import com.google.android.samples.socialite.di.AppCoroutineScope
import com.google.android.samples.socialite.widget.SocialiteWidget
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

@Singleton
class WidgetModelRepository @Inject internal constructor(private val widgetModelDao: WidgetModelDao, @AppCoroutineScope private val coroutineScope: CoroutineScope, @ApplicationContext private val appContext: Context) {

suspend fun create(model: WidgetModel): WidgetModel {
widgetModelDao.insert(model)
return widgetModelDao.loadWidgetModel(model.widgetId).filterNotNull().first()
}

fun loadModel(widgetId: Int): Flow<WidgetModel?> {
return widgetModelDao.loadWidgetModel(widgetId).distinctUntilChanged()
}

fun delete(appWidgetIds: IntArray) {
coroutineScope.launch {
appWidgetIds.forEach { appWidgetId ->
widgetModelDao.loadWidgetModel(appWidgetId).collect { model ->
if (model != null) {
widgetModelDao.delete(model)
}
}
}
}
}

fun updateUnreadMessagesForContact(contactId: Long, unread: Boolean) {
coroutineScope.launch {
widgetModelDao.modelsForContact(contactId).filterNotNull().forEach { model ->
widgetModelDao.update(WidgetModel(model.widgetId, model.contactId, model.displayName, model.photo, unread))
SocialiteWidget().updateAll(appContext)
}
}
}
}

0 comments on commit 920a557

Please sign in to comment.