Hi I want to send data from `BroadcastReciever()`...
# android
s
Hi I want to send data from
BroadcastReciever()
somewhere else, which can be
viewModel
,
repository
, or
fragment
. I am not sure where to send data from receiver because i am newbie to MVVM architecture. I have three questions: 1. Where to send data from
receiver
?
ViewModel
or
repository
? 2. How to send data by not breaking the best practices and MVVM. 3. Should i use
Coroutines
in receiver? If yes, how? I am a beginner so please tell me if question is unclear. Code examples will help me a lot. I have tried almost everything from Internet and not a single solution was easy to understand. Thank you!
p
I would say it depends on your use case. I would go with the repo, Activity/Fragments may not be present in the case of a Notification or a Bluetooth ON/OFF event. The repo is always accessible.
s
Can you please provide me any example of how to send data from receiver to repo? Thanks
p
A working example would take some time and I am a bit busy these days. The system creates the Broadcaster.class instance for you when an Intent matches your Broadcaster IntentFilter. The Broadcaster class has an onCreate() method on it, you are going to override it. Now: At that point you don't know if there are Activities open in your App(unless you monitor the Activities status separate). That is why I opt always to persist the event status/data in the database so when the App opens again it is there and you don't lose it. It of course depend on your case, you may allow to lose an event like Bluetooth ON/OFF, Network ON/OFF etc. So going back to how to the repo. From Broadcaster.onCreate() you will need a way to access the repo. It will depend on how you access the repo in your App. Do you use a dependency injection framework, you access it through a singleton or you just create a new Repo() instance. Just access it the same as you access it from an Interactor or a ViewModel
❤️ 2
s
Thanks a lot for your time and effort. I have solved the issue by injecting repo though hilt in broadcast receiver.
👍 1