Is it ok to use broadcast receiver just to refresh...
# android
r
Is it ok to use broadcast receiver just to refresh content of other activity? I have got a project where I found this. Check Thread.
🚫 1
😶 2
Copy code
/***
 * This will refresh my courses
 */
class MainActivityGotoHomeReceiver :
    BroadcastReceiver() {

    companion object {
        const val INTENT_FILTER = "main.activity.goto.home"
    }

    var mainActivity: MainActivity? = null
    override fun onReceive(context: Context?, intent: Intent?) {
        if (context != null) {
            val myCourseViewModel =
                ViewModelProvider(mainActivity!!).get(MainActivityViewModel::class.java)
            myCourseViewModel.gotoHomeFragment()
        }

    }
}
k
How about just using LocalBroadcastManager?
r
And a lot of receivers like this whenever he needed to do something in other activity than the current one he used receiver. I am not sure what the developer wanted to do.
Copy code
class MainActivityGotoLoginScreenReceiver() :
    BroadcastReceiver() {

    companion object {
        const val INTENT_FILTER = "main.activity.goto.login.screen"
    }

    var mainActivity: MainActivity? = null
    override fun onReceive(context: Context?, intent: Intent?) {
        if (context != null) {
            mainActivity?.finishAffinity()
            mainActivity?.startActivity(Intent(mainActivity,LoginActivity::class.java))
        }

    }
}
k
LocalBroadcastManager is useful within an app, while BroadcastReceivers are good for outside activities
r
What about this? https://developer.android.com/reference/androidx/localbroadcastmanager/content/LocalBroadcastManager This class is deprecated. LocalBroadcastManager is an application-wide event bus and embraces layer violations in your app: any component may listen events from any other. You can replace usage of
LocalBroadcastManager
with other implementation of observable pattern, depending on your usecase suitable options may be
LiveData
or reactive streams.
k
Yes, but you have to have access to the LiveData to listen for the events
But, reading your first comment, if you are trying to refresh the content, then LiveData is the way to go
r
Ok Thanks. I feel like the project has some serious problems.
k
Most projects do 🙂
r
Yeah, I guess I have go through a lot of refactoring. 🧐
You are right @kevindmoore. The problem here is he doesn't have access to that livedata he wants to update. Because two activities use two different ViewModels. Like He goes from Activity A -> Activity B then update something in remote from Activity B and when presses back button and goes back to Activity B he wants to see the updated data.