https://kotlinlang.org logo
#android-architecture
Title
# android-architecture
k

KayCee

09/10/2020, 8:54 AM
I am trying to apply the following function but it doesn't work is there anyone give a hint why: • In the time I receive notification on onReceive of broadcast receiver I call a function in a viewmodel (which is injected into my broadcast receiver) to set aLiveData.value = newValue. However, nothing happened in my fragment. • Then I try to use a local broadcast receiver: in my broadcast receiver on receive I sendBroadcast after notication came in, register it in fragment but it didn't work too. • The last option can be use update database in the time I get notification then observe it in my fragment, but I need to implement the dao, use case and so on I might be an overkill? I still want to figure out why the first 2 options don't work.
f

Fatih

09/10/2020, 12:59 PM
None of the solutions seems to be reasonable (maybe second option could work). How do you inject viewmodel into broadcast receiver?
Try to use
<http://aLiveData.post|aLiveData.post>
as you may have a threading issue. Although broadcast receivers run in
Main
thread, I am not sure in which thread you set
livedata
a

Alex Prince

09/10/2020, 1:26 PM
Also keep in mind that livedata will only fire if it's lifecycle owner is in a "good" lifecycle state to receive that update, so, if your fragment isn't in an active lifecycle state, it won't fire
g

gildor

09/11/2020, 8:05 AM
I would separate it into 2 parts: 1. receiveing broadcasts 2. notify fragment And to do so implement some repository for this with notify and observe methods, where broadcastreciever notifies by just calling
notify
method` and fragment observes it state with flow/observable/livedata
k

KayCee

09/11/2020, 8:25 AM
@Fatih I can see the id of view model and when I can see the log that tell me the function in the view model was successfully called, does that mean the injection was ok? I've known about injecting view model into broadcast receiver is kind of anti pattern. just give it a try. From customer requirement, they want if I set time of the notification is 3 p.m, so in exact 3 p.m if I am on the home fragment the UI should be updated. Even if the notification might not fired yet? I don't think that is possible , right? @gildor Thank you for your support. It seems that your general solution is the same with my 3rd options. @Alex Prince yeah sir, I know about that fact but sometimes I feel like I can control it. If we are on that fragment in which the live data is observing so I can listen when some place post the value to it. Is that correct?
g

gildor

09/11/2020, 8:45 AM
It doesn’t involve any database, but yeah, it closer to this solution I really think it’s better approach than connecting to broadcast receiver directly
🤔 1
5 Views