您可以製作基於緩存的圖層。您需要考慮是否希望它僅保存在內存中,或者保存在內存和磁盤上。
我提出了一個多級(內存,磁盤,網絡)緩存系統。我已經成功地使用了這個架構。它與單例類和c#事件一起工作。處理程序可以有許多訂戶 。因此,如果數據可用,UI屏幕可以預訂接收,並且每個請求可以多次調用 。其設計是儘可能快地從內存中返回數據,但仍然會通過磁盤和網絡調用刷新數據。 用戶界面可能會被回撥幾次,因爲它會使用內存中的數據快速回撥,並在網絡請求完成後再次回撥。爲了幫助線程安全,您可以使用鎖或使用線程安全集合(如ConcurrentDictionary或ConcurrentQueue)。還有很多邊緣情況需要考慮,但這是具有事件的多級緩存系統的基本架構。
// pseudo code
class CacheHelper
{
// todo: create singleton
RequestData()
{
if (data in memory)
{
// this quickly gets the app some data
Fetch data from dictionary/list/etc
NotifySubscribers(this, data)
}
if (data in disk)
{
// this gets data persisted after user force closes app then reopens
Fetch data from sqlite, file storage, etc
NotifySubscribers(this, data)
copy data from disk to memory
}
// always request data from server too to keep it fresh
RequestLatestDataFromServer(); // you can put a cap on this to limit network requests
}
HandleRequestLatestDataFromServerComplete(obj, args)
{
// this is the data returned from server
ALSO copy server result to memory and copy to disk
NotifySubscribers(this, data);
}
/// To use this in a UI class
ViewDidAppear()
{
CacheHelper.Instance.HandleRequestLatestDataFromServerComplete += ReceivedData;
}
ViewWillDisappear()
{
CacheHelper.Instance.HandleRequestLatestDataFromServerComplete -= ReceivedData;
}
void ReceivedData(Object obj, EventArgs args)
{
// update your UI
// This may get called a few times, for each level of cache retrieved
}
如果您的緩存系統適合您,也可以查看Akavache https://github.com/akavache/Akavache – jaybers