localbroadcastmanager is deprecated, use implementations of the observable pattern instead.
androidx.localbroadcastmanager
is being deprecated in version 1.1.0
Reason
LocalBroadcastManager
is an application-wide event bus and embraces layer violations in your app; any component may listen to events from any other component.
It inherits unnecessary use-case limitations of system BroadcastManager; developers have to use Intent even though objects live in only one process and never leave it. For this same reason, it doesn’t follow feature-wise BroadcastManager .
These add up to a confusing developer experience.
Replacement
You can replace usage of LocalBroadcastManager
with other implementations of the observable pattern. Depending on your use case, suitable options may be LiveData
or reactive streams.
Advantage of LiveData
You can extend a LiveData
object using the singleton pattern to wrap system services so that they can be shared in your app. The LiveData
object connects to the system service once, and then any observer that needs the resource can just watch the LiveData
object.
public class MyFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LiveData<BigDecimal> myPriceListener = ...;
myPriceListener.observe(this, price -> {
// Update the UI.
});
}
}
The observe()
method passes the fragment, which is an instance of LifecycleOwner
, as the first argument. Doing so denotes that this observer is bound to the Lifecycle
object associated with the owner, meaning:
If the Lifecycle object is not in an active state, then the observer
isn't called even if the value changes.
After the Lifecycle object is destroyed, the observer is
automatically removed
The fact that LiveData
objects are lifecycle-aware means that you can share them between multiple activities, fragments, and services.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("custom-event-name"));
– ShottonLocalBroadcastManager
has been deprecated. I replaced mine with the EventBus library which is much nicer, imo. – Anastassia