preface
I started my own JetPack journey for business reasons. I have to admit, after using it: it smells good. JetPack solves many of our headaches with an official solution. As a complete solution, JetPack is not enough to explain in a single article. As it is officially said:
The Android Jetpack component is a collection of libraries that are built to work together, but can also be used separately, while leveraging Kotlin language features to help you be more productive. Use all or mix and match!
So this is going to be a series of articles that will expand on what I’ve learned and thought about using JatPack. (Currently, the company project has been fully refactored with Kotlin and JetPack, so a lot of the code design will be integrated into our business, so it’s a matter of opinion.)
A little bit into the pit of JetPack: ViewModel
A bit into the pit of JetPack: Lifecycle
A little bit into the pit of JetPack: LiveData
A little bit into the pit JetPack: NetworkBoundResource for actual foreplay
A little bit into the pit JetPack (final chapter) : Actual COMBAT MVVM
The key parts of the article will focus on:
The body of the
I don’t want to see a shot in the bb, also can jump directly to the website: developer. The android, Google. Cn/topic/libra…
1. How to manage the lifecycle
Lifecycle’s emergence helps us solve the problem of Lifecycle management. This piece for our daily development is indeed a bit more pits, life cycle handling, it is easy to cause memory leaks. In order for our business code to be lifecycle aware, we might write a lot of code. For example, to give a Presenter the ability to perceive the lifecycle, we might do something like this:
public interface IPresenter {
void onCreate(a);
void onStart(a);
void onResume(a);
void onPause(a);
void onStop(a);
void onDestroy(a);
}
Copy the code
Then implement the interface and call it during the Activity/Fragment lifecycle to complete the work.
This way is completely ojbk. It’s easy to understand, and I’m not saying it’s good or bad, because no solution is perfect. So next, let’s take a look at the official way of thinking about Lifecycle.
2, Lifecycle
By the way, the problem that needs to be addressed here is lifecycle management. So after all still cannot escape some routine composition in it. Lifecycle is the same, as can be seen in the official explanation:
Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.
In a short paragraph, we can guess that the observer mode of thinking is responding to life cycle changes externally. Without further ado, feel it directly from the code.
2.1, use,
In terms of use, it is relatively simple. Implementing the LifecycleObserver interface:
/ / the official demo
class MyObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
fun connectListener(a) {
// TODO
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
fun disconnectListener(a) {
// TODO}}Copy the code
These two annotations indicate that when the onResume() method of the listening component is called, our annotated method here will also be called. (Of course, the premise is addObserver)
We have an observer, so let’s go find the observed. Obviously, the objects we want to look at are things that have lifecycles, such as our usual Activity/Fragment. In this case, we simply add the Observer to the actual object before onResume(), such as onCreate() :
override fun onCreate(savedInstanceState: Bundle?). {
lifecycle.addObserver(MyObserver())
}
Copy the code
OK, so our MyObserver can now respond to the methods under the corresponding lifecycle annotation.
However, I believe the friend who writes like this, come back to spray me! There will be no lifecycle!!
That’s right, our Activitiy/Fragment is not available… It doesn’t have that method at all.
2.2, androidx
Lifecyle calls this method in the Activity/Fragment:
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
Copy the code
Have a friend should carry a knife to come over, I tm have no this method! Brother Die, put the knife down, not no, import is different. Let’s take our time. The Fragment package I used was like this: Androidx.fragment.app; . See the signs? Androidx, yes, it’s a reprogrammed package to perfectly support JatPack.
Of course, it doesn’t have to be AndroidX.
Fragments and Activities in the Support Library 26.1.0 and later already implement the LifecycleOwner interface.
So, liters of library is OK. At this time a small partner may say: I don’t want to upgrade the library how to do. Good question, do not want to upgrade library, do not want to upgrade library.. Not at all.
I’m sure someone noticed that getLifecycle() is an interface so we can implement it ourselves? Yeah, that’s right… (This is bullshit)
This is the key to our customization.
2.3, LifecycleOwner
What if our Activity does not support getLifecycle()? Here’s the official code:
class MyActivity : Activity(), LifecycleOwner {
private lateinit var mLifecycleRegistry: LifecycleRegistry
override fun onCreate(savedInstanceState: Bundle?). {
super.onCreate(savedInstanceState)
mLifecycleRegistry = LifecycleRegistry(this)
mLifecycleRegistry.markState(Lifecycle.State.CREATED)
mLifecycleRegistry.addObserver(MyObserver())
}
public override fun onStart(a) {
super.onStart()
mLifecycleRegistry.markState(Lifecycle.State.STARTED)
}
override fun getLifecycle(a): Lifecycle {
return mLifecycleRegistry
}
}
Copy the code
That’s it. It’s over. To tell you the truth, there’s nothing left to tell.
From the code, we can see that the LifecycleRegistry is our Observer, it is initialized in the Activity that has the lifecycle, and our Observer is added () to it, There are also method calls such as markState(Lifecycle.state.created).
So needless to say, Lifecycle helps us manage the Lifecycle.
2.4. Summary
After these few pieces of code, I’m sure some of you have a good idea about Lifecycle. A standard Observer pattern: here LifecycleRegistry (the implementation class for Lifecycle that the system helped us implement) holds an Observer that wants to listen to the LifecycleOwner. Then, through markState(), it iterates through all the observers, notifying them of lifecycle changes.
3, the principle of
Having talked about common usage, let’s look at how it works. I have to say that Lifecycle is implemented in a rather cosy way and that all sorts of cosy operations are a bit of a blur.
We added comments to the MyObserver above, so let’s take a look at what the comments have brought us. Using the annotation generator, we can see the following class in the build:
public class MyObserver_LifecycleAdapter implements GenericLifecycleObserver {
final MyObserver mReceiver;
LifecycleObserverDemo_LifecycleAdapter(MyObserver receiver) {
this.mReceiver = receiver;
}
@Override
public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
mReceiver.onAny(owner,event);
if (event == Lifecycle.Event.ON_RESUME) {
mReceiver.connectListener();
}
if(event == Lifecycle.Event.ON_PAUSE) { mReceiver.disconnectListener(); }}public Object getReceiver(a) {
returnmReceiver; }}Copy the code
As is clear, we can see that onStateChanged(LifecycleOwner owner, lifecy.Event Event) uses the corresponding Event to call the method annotated in our MyObserver.
So here’s the question: Who calls onStateChanged? From the example above, we know that an Observer that can sense life cycles either uses the built-in Lifecycle(getLifecycle()) or implements it yourself (LifecycleOwner). Let’s look at the implementation principle of these two cases.
3.1. Customize LifecycleOwner
The source code for this step is relatively simple and straightforward. We can look directly at markState(LifecycleRegistry) in the LifecycleRegistry. After layer after layer of calls, we can discard some logical decisions and see some key things:
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
// There's nothing more to say, right?mLifecycleObserver.onStateChanged(owner, event); mState = newState; }}Copy the code
As you can see, this section makes a straightforward call to onStateChanged() in the annotated generation class to complete the lifecycle awareness.
3.2, getLifecycle ()
GetLifecycle (), again, returns a LifecycleRegistry. So, at first I thought that the system therefore made the same call to 3.1 in the corresponding lifecycle. But I find I’m still too young.
In the onCreate method of SupportActivity, we can see this call:
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}
Copy the code
Does it feel familiar? The use of fragments for lifecycle separation management is found in many frameworks. Let’s take a good look at the ReportFragment.
@Override
public void onResume(a) {
super.onResume();
dispatchResume(mProcessListener);
dispatch(Lifecycle.Event.ON_RESUME);
}
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceofLifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); }}}Copy the code
At this point, you’re back to the method in LifecycleRegistry.
The end of the
Of course, this is not enough for us, so Google has also come up with interesting modules such as ViewModel and LiveData that complement each other. The following article will go into: ViewModel.
I haven’t written for a long time. For one thing, I have been very busy recently. Secondly, I just started doing JetPack. Gradually found JatPack is more interesting in the process of learning. So I decided to take a look at JetPack.
This article can be regarded as my return to writing articles in the pilot article ~