Skip to content

Commit

Permalink
Fix crash on FavoritesObserver (#5335)
Browse files Browse the repository at this point in the history
Task/Issue URL: https://app.asana.com/0/1202552961248957/1208841273777750/f

### Description
Fix NPE when trying to get `AppWidgetManager.getInstance`

### Steps to test this PR
NA, code review
  • Loading branch information
aitorvs authored Dec 2, 2024
1 parent 8ebd7d8 commit 04e0326
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions app/src/main/java/com/duckduckgo/app/widget/FavoritesObserver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,36 @@ import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Context
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.coroutineScope
import com.duckduckgo.app.browser.R
import com.duckduckgo.app.di.AppCoroutineScope
import com.duckduckgo.app.lifecycle.MainProcessLifecycleObserver
import com.duckduckgo.common.utils.DispatcherProvider
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.savedsites.api.SavedSitesRepository
import com.duckduckgo.widget.SearchAndFavoritesWidget
import dagger.SingleInstanceIn
import javax.inject.Inject
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@SingleInstanceIn(AppScope::class)
class FavoritesObserver @Inject constructor(
context: Context,
private val savedSitesRepository: SavedSitesRepository,
@AppCoroutineScope private val appCoroutineScope: CoroutineScope,
private val dispatcherProvider: DispatcherProvider,
) : MainProcessLifecycleObserver {

private val instance = AppWidgetManager.getInstance(context)
private val appWidgetManager: AppWidgetManager? by lazy {
AppWidgetManager.getInstance(context)
}
private val componentName = ComponentName(context, SearchAndFavoritesWidget::class.java)

override fun onStart(owner: LifecycleOwner) {
appCoroutineScope.launch(dispatcherProvider.io()) {
savedSitesRepository.getFavorites().collect {
instance.notifyAppWidgetViewDataChanged(instance.getAppWidgetIds(componentName), R.id.favoritesGrid)
instance.notifyAppWidgetViewDataChanged(instance.getAppWidgetIds(componentName), R.id.emptyfavoritesGrid)
owner.lifecycle.coroutineScope.launch(dispatcherProvider.io()) {
appWidgetManager?.let { instance ->
savedSitesRepository.getFavorites().collect {
instance.notifyAppWidgetViewDataChanged(instance.getAppWidgetIds(componentName), R.id.favoritesGrid)
instance.notifyAppWidgetViewDataChanged(instance.getAppWidgetIds(componentName), R.id.emptyfavoritesGrid)
}
}
}
}
Expand Down

0 comments on commit 04e0326

Please sign in to comment.