Essentials: [Enhancement] Add sync support to SecureStorage

Created on 22 Jul 2019  路  4Comments  路  Source: xamarin/Essentials

Summary

SecureStorage provides an async API via GetAsync and SetAsync methods. Implement Get and Set to provide an analogous synchronous API for situations that don't need/want async/await.

API Changes

Add new APIs:

  • public static string SecureStorage.Get(string key)
  • public static void SecureStorage.Set(string key, string value)

Intended Use Case

async/await tends to 'infect a codebase' propagating throughout. Some codebases do not need the additional complexity of async calls. Since on most platforms the SecureStorage operations are not actually performed async, provide access to a direct synchronous implementation without an async wrapper.

feature-request not-on-roadmap

Most helpful comment

I agree with @scotru
The Ios and Android version are synchronous.

We are migrating from xamarin.auth accountstore (in which the calls were synchronous) to xamarin.essentials.securestorage, and the async part is a real pain for our implementation.

@jamesmontemagno could you please reconsider?

All 4 comments

Thanks for the recommendation. How we implement the API is based on what each platforms implementations are. Since UWP and potentially others in the future require a Task to be returned this is the API that we have implemented and available for developers. So at this time we will not adjust or make changes to the API.

How we implement the API is based on what each platforms implementations are.

Doesn't really seem true, since the two most popular platforms iOS and Android implement this synchronously--only UWP has an async implementation. And there is not really any cost to exposing the synchronous version. But I respect your decision.

I agree with @scotru
The Ios and Android version are synchronous.

We are migrating from xamarin.auth accountstore (in which the calls were synchronous) to xamarin.essentials.securestorage, and the async part is a real pain for our implementation.

@jamesmontemagno could you please reconsider?

Had the same issue, I needed it to be sync. Ended up adding my custom wrapper around the API.

using System.Threading.Tasks;
using Xamarin.Essentials;

namespace App.Custom
{
    public static class SecureStorageCustom
    {
        public static string Get(string key)
        {
            Task<string> task = Task.Run(async () => await SecureStorage.GetAsync(key));
            return task.Result;
        }

        public static void Set(string key, string value)
        {
            Task task = Task.Run(async () => await SecureStorage.SetAsync(key, value));
            task.Wait();
        }
    }
}
Was this page helpful?
0 / 5 - 0 ratings