Two ways for rxjava to implement three-level cache in Android

As mentioned in the title of this article, rxjava is used to realize the three-level cache of data, namely memory, disk and network. I just recently watched the Android source code design pattern analysis and actual combat (inspired by the design of imageloader).

I put the code into my hot project, GitHub address

Source download address: rxjava_ jb51.rar

1. Use concat () and first () operators.

2. Use behaviorsubject.

Let's talk about the implementation method of behaviorsubject first. Without much nonsense, go directly to the code,

The most important one is the subscriptiondata () method, which is to judge whether the cache exists. If it exists, it will return the data in memory, and then judge whether the disk data exists. If it exists, it will return. If the first two do not exist, it will get the data from the network. And the most important thing is that when you get data from the network, remember to save it in memory and disk, and assign it to memory when you get data from disk.

Next, let's talk about the implementation of concat () and first () operators. I'm watching the Android source code design pattern analysis and practice. The author introduces the design of imageloader in the first chapter.

In memory storage is implemented by lrucache, and disk storage is serialization storage.

1. Define an interface:

2. Implementation of memory storage

3. Implementation of disk storage

Iscachedatafailure() method is to judge whether the current data is invalid. I divide WiFi status and non WiFi status according to the current network status. The expiration time of data in WiFi status is relatively short, and that in other status is relatively long.

4. Design of cacheloader

5. Networkcache obtained from the network:

6. Let's see how to use it

Be sure to give a key. I get data according to the key and give a type.

However, the cache I designed is still not ideal. What I want to achieve next is that I don't need to specify the class of the class when passing in. If there is a good implementation method, please tell me.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>