I am working on an application with xamarin forms cross platform, well I am using a menu whose information is obtained from a rest api, to avoid that each time a call is made to the menu an api query is made I decided to use a singleton, however It does not return the data from the api, it is worth mentioning that if I do not use the singleton it does bring the data. The code looks like this
Model-CategoriesModel
public partial class CategoriesModel
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("parent_id")]
public long ParentId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("is_active")]
public bool IsActive { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("level")]
public long Level { get; set; }
[JsonProperty("product_count")]
public long ProductCount { get; set; }
[JsonProperty("children_data")]
public List<CategoriesModel> ChildrenData { get; set; }
}
public partial class CategoriesModel
{
public static CategoriesModel FromJson(string json) => JsonConvert.DeserializeObject<CategoriesModel>(json, PetandLove.Model.Converter.Settings);
}
I have a ViewModel that makes the query even in api rest that is in a different class. ViewModel- MenuSpeciesViewModel
ConectionApiMagento category = new ConectionApiMagento();
public CategoriesModel categoryModel { get; set;}
public MenuEspeciesViewModel()
{
getCategory();
}
public async void getCategory()
{
categoryModel = await category.GetCategories();
}
Class that makes the connection- ConectionApiMagento.cs
public class ConectionApiMagento
{
static readonly HttpClient cliente = new HttpClient();
public async Task<CategoriesModel> GetCategories()
{
string url = "url";
var resultado = await cliente.GetAsync(url);
var json = resultado.Content.ReadAsStringAsync().Result;
CategoriesModel item = CategoriesModel.FromJson(json);
return item;
}
}
Singleton
public class MenuSinlgeton
{
#region Properties
private static MenuSinlgeton _instance = null;
public MenuEspeciesViewModel Especies { get; set;}
#endregion
public MenuSinlgeton()
{
Especies = new MenuEspeciesViewModel();
}
#region methods
internal static MenuSinlgeton Instance()
{
if (_instance==null)
{
_instance = new MenuSinlgeton();
}
return _instance;
}
#endregion
}
The call to the singleton is made in the app.xmal.cs constructor and in the class where the data is drawn. I use this call. MenuSinlgeton Especies = MenuSinlgeton.Instance();
In essence I would like the singleton to have the data that the api returns so that I can use it an infinite number of times with just one api call, I don't get errors only when I try to use the data that the singleton is supposed to bring.
I took the liberty of modifying your code to make it work. I hope it helps you or at least to take it as a guide for a solution.
Then you can make the call