2017-09-13 58 views
1

我對移動開發和Xamarin相對較新。我正在製作一個應用程序,他們完全依賴於REST API,並且很清楚,由於恆定負載,儘管它們速度很快,但單擊應用程序是一個非常糟糕的體驗。用於減少等待(Xamarin)應用程序中REST調用的本地預加載和緩存層?

我想到的解決方案是在用戶加載應用程序然後緩存很短時間內調用許多端點異步。

我可以很容易地實現這一點,但我最終會重新投資一個問題,我認爲每個應用程序都使用REST API。

所以我的問題是

什麼是預加載的最常用的方法和緩存REST數據(Xamarin)應用程序?

它是在應用程序本地服務區之間創建一個緩存層,然後啓動一個異步任務來緩存我們希望用戶打開的端點?

回答

1

您可以製作基於緩存的圖層。您需要考慮是否希望它僅保存在內存中,或者保存在內存和磁盤上。

我提出了一個多級(內存,磁盤,網絡)緩存系統。我已經成功地使用了這個架構。它與單例類和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 
} 
+0

如果您的緩存系統適合您,也可以查看Akavache https://github.com/akavache/Akavache – jaybers

相關問題