1

I have an application where i want to trigger a notification , notification data comes from an api request , i'm using mvvm pattern with which i'm injecting the viewmodel using dagger-hilt , it works well in my activities and fragments but when i tried to inject it into my broadcast receiver , it is not working and i don't know what is actually wrong with the code , any help is appreciated guys , thank you .

  • This is the code

@AndroidEntryPoint
class AlarmReceiver  :  BroadcastReceiver () {
   @Inject lateinit var leagueViewModel : LeagueViewModel
   override fun onReceive(context: Context?, intent: Intent?) {
       AlarmHelper.setAlarm(context!!)
       if(Constants.checkConnectivity(context)){
           if(intent?.action == "intent.action.android.games"){
               //Using the viewmodel insid this function to get data from api
               fireGameNotification(context,leagueViewModel)              
           }
       }
   }
  • This is the error occuring
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
Taki
  • 3,290
  • 1
  • 16
  • 41
  • in other classes like Activity/Fragment it's work? – i30mb1 Nov 05 '20 at 07:14
  • 1
    It's not good idea to use Viewmodel in BroadcastReceiver https://stackoverflow.com/a/51007347/11085663 – Saeid Lotfi Nov 05 '20 at 10:01
  • Thank you guys for answering , well yeah i was told to not use it in Broadcast receiver as it is not good practice , so i move the code to my activity , thank you – Taki Nov 05 '20 at 17:15

1 Answers1

0

My approach for this is:

  1. When receive the broadcast, save the data into DataStore (replacement of SharedPreference) or Room database.

  2. Observe the DataStore or database changes in your ViewModel (using Flow or LiveData).

Sam Chen
  • 7,597
  • 2
  • 40
  • 73