Call back from Dependency Services to Xamarin Forms

Hi all,
I have some platform specific code for iOS and Android, and call these code(method) using Dependency Services from Xamarin Forms.
I am able to call my DS without any issue as:
DependencyService.Get().GetUser();

But i am try to call in/as a way to Dependency services to call back some method from my Xamarin Form code after done their work.

No idea how to do?

Answers

  • adamkempadamkemp USInsider, Developer Group Leader mod

    There are several ways to do this:

    1. Pass in a callback as an argument.
    2. Passin an interface (which you implement) as an argument.
    3. Have the method return a Task.

    The third option is probably the best for this because it plays very nicely with async/await:

    private async Task DoSomethingAsync()
    {
        var result = await DependencyService.Get<ISomethingDoer>().DoSomethingPlatformSpecificAsync();
        // Use the result
    }
    

    Your implementation would look something like this:

    public async Task<int> DoSomethingPlatformSpecificAsync()
    {
        await SomePlatformSpecificThingAsync();
    
        return 5;
    }
    
Sign In or Register to comment.