Search code examples
xamarinxamarin.formscross-platformakavache

How to subscribe new value in Akavache?


I'm using Akavache's GetAndFetchLatest method and I have created dependency services to communicate with Akavache's method. I'm calling akavache from service layer successfully when i directly reference. For subscribing

  MyMod result = null;
                var cache = BlobCache.LocalMachine;
                var cachedPostsPromise = cache.GetAndFetchLatest(
                    "mykey",
                    () => GetInfo(),
                    offset =>
                    {
                      //some condition
                    });

                    cachedPostsPromise.Subscribe(subscribedPosts => {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                           //do sothing.

                        });
                });

                result = await cachedPostsPromise.FirstOrDefaultAsync();
                return result;

It works.But how an I call subscribe on service layer with interface/dependency service?


Solution

  • Please find the the sample code :

    var result = BlobCache.LocalMachine;
                var cachedPostsPromise = cache.GetAndFetchLatest(
                    "mykey",
                    () => ViewModelLocator.GetInstance<IYourServiceName>().MethodName(),
                    offset =>
                    {
                      //some condition
                    });
    
                    cachedPostsPromise.Subscribe(subscribedPosts => {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                           //Your piece of code
    
                        });
                });
    
                result = await cachedPostsPromise.FirstOrDefaultAsync();
                return result;
    

    Please note the there any anything inside subscribed will be called twice : first set of data will be cache and second set will be freshly fetched from server.You have to manage according.