Working example MvxRestClient.MakeRequestAsync with MvxJsonRequest

I just started working with Mvvmcrossin the base library for a multi-platform project.

I want to use a plugin Mvvmcross.Networkwith a plugin Mvvmcross.Json, but I cannot find a good example combining these two plugins. I watched all the N + 1 videos, and I assume that this was not implemented at the time the video was uploaded.

Ideally, I would like to know how to make an asynchronous request using json request and json response.

Thanks in advance

+4
source share
1 answer

, Mvvmcross (Mvx) 4.1.4 4.2.2. , readme, IMvxJsonRestClient IMvxRestClient. (Commit: a5561b fb2feb7), , , .


MvvmCross.Plugins.Json JSON, MvxJsonRestClient MvxRestClient.

MvxJsonRestClient JSONPlaceholder API:

-

Mvx 4.1.4 , , 4.2.2.

public void PostSample()
{
    var request = new MvxJsonRestRequest<UserRequest>
        ("http://jsonplaceholder.typicode.com/posts")
    {
        Body = new UserRequest
        {
            Title = "foo",
            Body = "bar",
            UserId = 1
        }
    };

    var client = Mvx.Resolve<IMvxJsonRestClient>();
    client.MakeRequestFor(request,
        (MvxDecodedRestResponse<UserResponse> response) =>
        {
            // do something with the response.StatusCode and response.Result
        },
        error =>
        {
            // do something with the error
        });
}

- Async

Async Mvx 4.1.4 .

public async Task PostSampleAsync()
{
    var request = new MvxJsonRestRequest<UserRequest>
        ("http://jsonplaceholder.typicode.com/posts")
    {
        Body = new UserRequest
        {
            Title = "foo",
            Body = "bar",
            UserId = 1
        }
    };

    var client = Mvx.Resolve<IMvxJsonRestClient>();
    var response = await client.MakeRequestForAsync<UserResponse>(request);

    // Check response.StatusCode if matches your expected status code
    if (response.StatusCode == System.Net.HttpStatusCode.Created)
    {
        // interrogate the response object
        UserResponse user = response.Result;
    }
    else
    {
        // do something in the case of error/time-out/unexpected response code
    }
}

public class UserRequest
{
     public string Title { get; set; }
     public string Body { get; set; }
     public int UserId { get; set; }
}

public class UserResponse
{
     public string Title { get; set; }
     public string Body { get; set; }
     public int UserId { get; set; }
     public int Id { get; set; }
 }
+2

Source: https://habr.com/ru/post/1650278/


All Articles