cool hit counter Retrofitting the official Android architecture component ViewModel_Intefrankly

Retrofitting the official Android architecture component ViewModel

Original article address:


The official Android architecture components were announced at the Google I/O conference in May this year, and were in beta until November. Due to my busy schedule, I only read similar articles, but did not use them in real projects, let alone read the source code, so I was not familiar with the use of these components, and also felt that they were very high level and mysterious!

Until the official Android architecture component was released in November, and Google was Support Library v26.1.0 after of version in Embedded with Android Official Architecture Components in of Life Cycle Components, I think, these be trends, since Google That's what I think., Then I'll do the same. be time to learn a wave and introduce them into MVPArms The framework is up.

Github : you of Star be I insist. of power ✊

brief introduction

Because of the desire to bring the official Android architecture components into MVPArms framework her in, So I studied hard. Android Official Architecture Components in apart from Room apart from of All source code, Based on an examination of be No the whole component is suitable for introducing MVPArms framework

(located) at After studying the source code, find that Android The official architecture component is not really imagined of So profound., Principle instead be we (located) at Daily development in All of them will be used of knowledge point, Then I will. (located) at essay of Start with a brief of Introducing. Android Official Architecture Components in of These components


Life Cycle Components be Android Official Architecture Components in of Core Components, It can make various instances as observers together with Activity harmony Fragment components with lifecycle characteristics, such as the LiveData harmony ViewModel (not) at all be Based on this component, put it briefly be, You will need to bind the life cycle of Instances are registered to the component, The component then will be in You specify. of A life cycle method execute Notify this instance when

There are many scenarios, such as the one previously described in MVP In the architecture, you need to add the following to the Activity execute onCreate When, let Presenter initialize some operations, there's no need to add a new operation to the Activity of onCreate and then call Presenter method, which can be done directly using the official lifecycle component, in the Activity execute onDestroy You can also use the lifecycle component when you need to release some of the object's resources.


LiveData Has two functions, The first function be observer pattern, (located) at Value Notify previous registrations when changes occur of All Observers, Second function be Lifecycle-based components together with Activity harmony Fragment components with lifecycle characteristics, such as the (located) at Stops when life cycle changes occur perhaps Before recovery of events

put it briefly be, When a page requests network data successfully, it needs to be synchronized UI , but the page is no longer visible, at which point it will stop syncing. UI specific operation


ViewModel There are two functions, the first of which enables ViewModel and ViewModel The data in the screen rotation or configuration change caused by the Activity The second feature that helps developers to easily implement the rebuilt data to survive the rebuild and continue to use it afterwards is Fragment together with Fragment Between, Activity together with Fragment among of news story and Shared data

A brief look at the official architecture components

Without further ado, the use of such articles and Demo There's too much., Understand them. of functionalities harmony After the application scenario, We just learned about them. be sincere of suit oneself of need, rather than be follow the crowd blindly, Here I'll break down what I be How to examine new technologies , and How to judge these new technologies be Is it necessary to apply to yourself of sports event in


The lifecycle components are described above of functionalities, Here's a breakdown of the lifecycle components be Is it necessary to introduce me of framework MVPArms

Speaking of life cycles I was reminded of my previous work at Is a traditional MVP really convenient or cumbersome to use in a project? in discussions of A content

The popular ones on the market now MVP There are two architectures, first type be will Activity perhaps Fragment act as View, abstract a Presenter layer out, second type be will Activity perhaps Fragment act as Presenter, abstract a View layer out

The first type of representative of framework have MVPArms , the second type of framework represented by TheMVP , of course the first type of MVP What are the advantages of the second type of architecture, which is the most used in the market?

As I said in the article above, there are two main advantages, Easy reuse of View , and direct access together with Activity perhaps Fragment of Life cycle do bind , so that it can be used directly Activity perhaps Fragment of life cycle, No need to go through the extra of retrace, Of course there's a downside., me (located) at essay in Also described, interested of You can check it out.

Type 1 of MVP infrastructure be does not have the ability to harmony Activity perhaps Fragment of Life cycle direct do binding of strengths of, so very be The second type of jealousy of MVP infrastructure, this too be Two types of MVP The biggest difference in the architecture, but you're right in thinking that using lifecycle components now makes the first type of MVP It's easy to structure of Has a binding lifecycle of strengths, current (located) at Type 1 of MVP The architecture will be like a tiger with wings

After the above of analysis, I think the lifecycle component is important for me of framework have one's say be It's necessary. of, This will make daily development easier


LiveData together with RxJava (not) at all be Based on the observer pattern, There is also functional overlap, Google (located) at The official documentation also clearly states, If you are (located) at use RxJava, Agera and similar functions of warehouse, If only you could get it right. of Processing data streams of life cycle, It would be perfectly acceptable to continue using them instead of LiveData

Note: If you are already using a library like RxJava or Agera, you can continue using them instead of LiveData. But when you use them or other approaches, make sure you are handling the lifecycle properly such that your data streams pause when the related LifecycleOwner is stopped and the streams are destroyed when the LifecycleOwner is destroyed. You can also add the android.arch.lifecycle:reactivestreams artifact to use LiveData with another reactive streams library (for example, RxJava2).

As you can see from the official documentation Google in response to this of Recommendation on be RxJava, Agera, LiveData and other libraries with similar functionality, you can use just one

option RxJava also be LiveData ?

LiveData harmony RxJava I do agree with Google's official advice that it is better to choose one of the two, rather than introducing both, and that MVPArms framework, which also happens to introduce the RxJava So I'm also going to analyze in MVPArms framework in particulars LiveData also be RxJava?

So I studied the source code carefully, LiveData has two functions, notifying observers of updated data and stopping and resuming previous events according to the life cycle, while Rxjava add into RxLifecycle, RxJava add into AutoDispose, perhaps Rxjava add into Life Cycle Components, It can also be easily done based on the life cycle stop harmony Before recovery of events, (located) at With it Rxjava powerful specific operation symbol, LiveData What you can do RxJava It can all be done, LiveData No What you can do RxJava Can also do

furthermore RxJava Not just be RxJava, He also be A huge one of Ecological chain, He still has RxCache, RxLifecycle, RxAndroid, RxPermission, Retrofit-Adapter We have a vast and powerful library of derivatives, such as the one we have left to do many things that are very inconvenient for the newborn, untalented LiveData compared to RxJava There would be no advantage, and it would even look very rudimentary.

therefore LiveData harmony RxJava If I had to choose between them, I wouldn't have any reason to. LiveData


ViewModel in There's a feature that makes me amazing, I'm curious, too, It can make ViewModel and ViewModel The data in the screen rotation or configuration change caused by the Activity This feature is very useful and important, because there is no official solution before, so I think it is necessary to introduce this feature. MVPArms framework

Also another feature, which helps developers to easily implement Fragment together with Fragment Between, Activity together with Fragment among of news story and Shared data, It's also positive be I need it of Official solution

but (located) at I'll go on with my research, Ready to introduce it to the project in time, find that Google Make this function highly encapsulated and restrict it of Scope of use, merely can be used for ViewModel

But I thought Google could make MVVM in the framework of the ViewModel with these features, so why can't I extend this functionality to provide MVP in the framework of the Presenter, And even more of module?

So I studied the source code carefully, Prepare to modify the source code and encapsulate it into a library of manner, Let's make it more of Developers (located) at more of These features can be used in the scene

remodel ViewModel component

To transform ViewModel component Naturally, you have to analyze the entire source code, to know how it works, to know how to do it.

Analyze the source code

Space is limited, It's as simple as that of Analyze the source base, The source code is actually a few classes, It's layered, The core code is on (located) at One is called HolderFragment of Fragment in,

in my opinion ViewModel component of The core principle is also be HolderFragment in of One-line code implementation of:


setRetainInstance(boolean) be Fragment in of One method, I think a lot of people should know this method of significance

Simply setting this method to true will make the current Fragment (located) at Activity rebuild survive, If not set perhaps is set to false, current Fragment will be in Activity rebuild the same thing happens rebuild, so that it was newly created of Object overrides

meaning be Just set this method to true, Fragment and Fragment All data in the Activity rebuild survive

At this point we are in setRetainInstance(boolean) for true of Fragment in Put a dedicated storage for ViewModel of Map , Nature Map in all of ViewModel All will be spared from Activity rebuild

in be We let Activity, Fragment All tied to one of these of Fragment , will ViewModel Store it in this Fragment of Map in, ViewModel component That's how it happened.

How to remodel

fancy knowing How to remodel, Then we need to be clear about this renovation of final destination of be What the, we of eye of only be Let's make it ViewModel component can be used for Presenter, And even more of module, more than be For ViewModel

Then why Google official of ViewModel component No can be used for What about the other modules?, You can tell by reading the source code, be Because Google Mention it above of Map, encapsulated, and did not offer to go out, furthermore limit ViewModel The way it was constructed

ViewModel component Let a new ViewModel must be inherited from it of The base class, furthermore Let the developer must provide one Factory specify ViewModel The way it was constructed, ViewModel component At the right time, they'll take the initiative to go to the right place. Factory construct (sth abstract) ViewModel instance, and put it in the Map in

At this point the whole construct (sth abstract) The process is all ViewModel component In control and confined to ViewModel, So I need to do it of only be will Map harmony ViewModel The way it was constructed Expand out , will more of Control to the outside of Developers

put into practice

After the above analysis, the idea and solution are available, and the next step is how to implement them

in be I analyze it in conjunction with the above of thinking harmony The programme has adapted and appropriately adapted the official source code of optimize, LifecycleModel And so it was born.

This article is mainly also be speak (located) at Before you complete a goal, (located) at from 0 arrive 1 period of thinking harmony analysis of process, As for the details you are interested in of Words back be Go see me of Source put, Ha ha, The comments are very detailed!

Github : you of Star be I insist. of power ✊


A new technology be sincere of suitable for themselves yet be You need to look at it yourself, You shouldn't blindly follow the trend, If you only know this technology is hot then use it, I don't know why I used it, Use it of advantage, Then you'll always be in passive learning of awkward situation, always (located) at do, but be I always feel like I'm not up to date of progress, feel apprehensive, these be Most of the modern technops exist (located) at of Situation

lit. step on a pit

(located) at The actual project in use ViewModel component I also encountered some problems, and wasted a lot of my time, so it is necessary to share it so that you do not have to take the wrong path

Pitfalls when getting ViewModel via Activity:

  • ActivityLifecycleCallbacks, the ViewModel obtained in the onActivityCreated method is a new instance of the reconstructed ViewModel every time the Activity is rebuilt, which does not save the ViewModel and the data in the ViewModel from being rebuilt by the Activity, so do not obtain the ViewModel in this method.
  • (located) at Activity of onDestroy method in Cannot get ViewModel, will report the error

Pass Fragment fetch ViewModel encountered of pit:

  • (located) at FragmentManager.FragmentLifecycleCallbacks in of onFragmentAttached method in fetch ViewModel will also appear harmony Activity The same of circumstance, fetch of ViewModel be anew construct (sth abstract) after of The new instance, ViewModel and ViewModel in of Data is not immune Activity rebuild, So don't (located) at this method in fetch ViewModel
  • The onFragmentDestroyed method in FragmentManager.FragmentLifecycleCallbacks also cannot fetch the ViewModel, it will report an error
  • Cannot get ViewModel in Fragment's onDestroy method, will report error

Hello My name is Jessyan, if you like my articles, you can follow me on the following platforms

-- The end

1、Mission Bound Indepth Analysis of WCFs Reliable Sessions Protocol Chapter below
2、On the Fundamental Flaws of Reinforcement Learning
3、Adding a LiveRe commenting system to the Hexo blog
4、42 Create RDD
5、SpringExpressionLanguage SpEL Quick Reference Guide

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送