In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what are the advantages of Android LiveData". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what are the advantages of Android LiveData.
LiveData is a data holder class that holds a value and allows you to observe it. Unlike ordinary observers, LiveData follows the life cycle of application components so that Observer can specify a Lifecycle that it should adhere to.
If the Lifecycle of the Observer is in the STARTED or RESUMED state, LiveData considers the Observer active.
Public class LocationLiveData extends LiveData {private LocationManager locationManager; private SimpleLocationListener listener = new SimpleLocationListener () {@ Override public void onLocationChanged (Location location) {setValue (location);}}; public LocationLiveData (Context context) {locationManager = (LocationManager) context.getSystemService (Context.LOCATION_SERVICE) } @ Override protected void onActive () {locationManager.requestLocationUpdates (LocationManager.GPS_PROVIDER, 0,0, listener);} @ Override protected void onInactive () {locationManager.removeUpdates (listener);}}
The implementation of Location snooping has three important parts:
OnActive (): this method is called when the LiveData has an active observer, which means that you need to start updating from the device's viewing location.
VonInactive (): this method is called when the LiveData does not have any active observers. Since there is no observer listening, there is no reason to maintain a connection to the LocationManager. This is important because staying connected consumes significant power and does not have any benefits.
SetValue (): call this method to update the value of the LiveData instance and notify the active observer of the change.
You can use the new LocationLiveData as follows:
Public class MyFragment extends LifecycleFragment {public void onActivityCreated (Bundle savedInstanceState) {LiveData myLocationListener =...; Util.checkUserStatus (result-> {if (result) {myLocationListener.addObserver (this, location-> {/ / update UI});});}}
Notice that the addObserver () method passes LifecycleOwner as * parameters. Doing so indicates that the observer should bind to the Lifecycle, meaning:
If the Lifecycle is not active (STARTED or RESUMED), the observer is not called even if the value changes.
If the Lifecycle is destroyed, the observer is automatically removed.
The fact that LiveData is lifecycle awareness gives us a new possibility: it can be shared among multiple activity,fragment and so on. To keep the instance simple, you can use it as a singleton, as shown below:
Public class LocationLiveData extends LiveData {private static LocationLiveData sInstance; private LocationManager locationManager; @ MainThread public static LocationLiveData get (Context context) {if (sInstance = = null) {sInstance = new LocationLiveData (context.getApplicationContext ());} return sInstance;} private SimpleLocationListener listener = new SimpleLocationListener () {@ Override public void onLocationChanged (Location location) {setValue (location) }; private LocationLiveData (Context context) {locationManager = (LocationManager) context.getSystemService (Context.LOCATION_SERVICE);} @ Override protected void onActive () {locationManager.requestLocationUpdates (LocationManager.GPS_PROVIDER, 0,0, listener);} @ Override protected void onInactive () {locationManager.removeUpdates (listener);}}
Now fragment can use it like this:
Public class MyFragment extends LifecycleFragment {public void onActivityCreated (Bundle savedInstanceState) {Util.checkUserStatus (result-> {if (result) {LocationLiveData.get (getActivity ()). Observe (this, location-> {/ / update UI});});}}
There may be multiple fragment and activity observing MyLocationListener instances, and LiveData can canonically manage them so that they connect to system services only when any one of them is visible (that is, active).
LiveData has the following advantages:
No memory leaks: because Observer are bound to their own Lifecycle objects, they can be cleaned up automatically when their Lifecycle is destroyed.
Do not crash because activity stops: if Observer's Lifecycle is idle (for example, when activity is in the background), they will not receive a change event.
Always keep data *: if Lifecycle restarts (for example, activity returns to startup status from background), it will receive location data of * (unless it is not already available).
Handle configuration changes correctly: if activity or fragment is recreated due to configuration changes (such as device rotation), it will immediately receive valid location data for *.
Resource sharing: you can keep only one instance of MyLocationListener, connect to the system service only once, and correctly support all observers in the application.
No longer manually manage the lifecycle: fragment just observes the data when needed, without worrying about being stopped or starting observation after it is stopped. Because fragment provides its Lifecycle when observing the data, LiveData automatically manages all of this.
Conversion of LiveData
Sometimes you may need to change the value of the LiveData before sending it to the observer, or you may need another LiveData to return a different LiveData instance.
The Lifecycle package provides a Transformations class that contains helper methods for these operations.
,% 20android.arch.core.util.Function
LiveData userLiveData =...; LiveData userName = Transformations.map (userLiveData, user-> {user.name + "" + user.lastName})
,% 20android.arch.core.util.Function
Private LiveData getUser (String id) {...;} LiveData userId =...; LiveData user = Transformations.switchMap (userId, id-> getUser (id))
The use of these transformations allows the observer's Lifecycle information to be carried throughout the call chain so that these transformations are operated only when the observer observes the return of the LiveData. This lazy operational nature of the transformation allows implicit lifecycle-related behavior to be passed without the need to add explicit calls or dependencies.
Whenever you think you need a Lifecycle class in ViewModel, the transformation may be the solution.
For example, suppose you have a UI, and the user enters an address and then receives the zip code for that address. The simple ViewModel of the UI might look like this:
Class MyViewModel extends ViewModel {private final PostalCodeRepository repository; public MyViewModel (PostalCodeRepository repository) {this.repository = repository;} private LiveData getPostalCode (String address) {/ / DON'T DO THIS return repository.getPostCode (address);}}
In the case of an implementation like this, UI needs to log out of the previous LiveData and re-register to the new instance each time getPostalCode () is called. In addition, if the UI is recreated, it will trigger a new repository.getPostCode () call instead of using the result of the previous call.
Instead of using that way, you should implement the conversion of address input into zip code information.
Class MyViewModel extends ViewModel {private final PostalCodeRepository repository; private final MutableLiveData addressInput = new MutableLiveData (); public final LiveData postalCode = Transformations.switchMap (addressInput, (address)-> {return repository.getPostCode (address);}); public MyViewModel (PostalCodeRepository repository) {this.repository = repository} private void setInput (String address) {addressInput.setValue (address);}}
Notice that we even make the postalCode field public final because it will never change. PostalCode is defined as the transformation of addressInput, so when the addressInput changes, if there is an active observer, repository.getPostCode () will be called. If there is no active observer at the time of the call, no operation will be performed until the observer is added.
This mechanism allows LiveData to be created with fewer resources and lazy operations as needed. ViewModel can easily get LiveData and define transformation rules on them.
Create a new transformation
More than a dozen different specific transformations may be used in the application, but they are not provided by default. You can use MediatorLiveData to implement your own transformations, and MediatorLiveData is specifically created to properly listen to other LiveData instances and handle the events they emit. MediatorLiveData needs to pay special attention to correctly passing it to the source LiveData that it is active / idle. See the Transformations class for more information.
At this point, I believe you have a deeper understanding of "what are the advantages of Android LiveData". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.