How to return a value after making the request with OAuth2Request?

518 Views Asked by At

I'm trying to return the value of an object but it returns null, however it returns a value in the request.

using System;
using Xamarin.Auth;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;

namespace RegistroAgil_Couchbase.Droid
{
    public class UserInfoRepository
    {
        public OAuthUserInfo Get()
        {
            var mainActivity = Forms.Context as MainActivity;
            var accounts = AccountStore.Create(mainActivity).FindAccountsForService("Facebook");
            var enumerable = accounts as IList<Account> ?? accounts.ToList();
            var account = enumerable.FirstOrDefault () == null ? null : enumerable.First ();

            if (account == null) {
                return null;
            } else {
                var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, account);

                JObject obj = new JObject ();

                request.GetResponseAsync ().ContinueWith (t => {
                    if (t.IsFaulted)
                        Console.WriteLine ("Error: " + t.Exception.InnerException.Message);
                    else {
                        obj = JObject.Parse (t.Result.GetResponseText ());

                        Console.WriteLine(obj["name"]); // <-- Here returns a value.
                    }
                });

                return new OAuthUserInfo {
                    AuthName = (string)obj ["name"] // <-- Returns null.
                };
            }
        }
    }
}

I’d really appreciate any help anyone can provide. Thanks in advance!

1

There are 1 best solutions below

2
On BEST ANSWER

1.

var waitEvent = new AutoResetEvent(false);

before line

request.GetResponseAsync ().ContinueWith (t => {

2.

waitEvent.Set();

after

obj = JObject.Parse (t.Result.GetResponseText ());

3.

waitEvent.WaitOne();

before

return new OAuthUserInfo {

Or

method should be

public async Task<OAuthUserInfo> Get()

and call to request

var object = await request.GetResponseAsync ();