Get Crypto Assets from GraphQL Backend
Now that we've created a UI that can display our Crypto assets, let's write the logic to retrieve the data from our GraphQL Backend.
1. GetAssestsQuery.graphql
Let's first see how StrawberryShake automatically generates C# code based on our *.graphql
files
In Visual Studio, open Services/GraphQL/Operations/GetAssestsQuery.graphql
Here's a breakdown of how Strawberry Shake turns this GraphQL query into C# code:
GetAssestsQuery.graphql Strawberry Shake query GetAssestsQuery($after: String)
Generates a Method, GetAssestsQuery.ExecuteAsync(string? after, CancellationToken token)
assets
Generates an interface, interface IGetAssestsQuery_Assets
nodes
Generates an interface, interface IGetAssestsQuery_Assets_Nodes
price
Generates an interface, interface IGetAssestsQuery_Assets_Nodes_Price
pageInfo
Generates an interface, interface IGetAssestsQuery_Assets_PageInfo
2. Add GetAssestsQuery Logic
In Visual Studio, open Services/GraphQL/CryptoGraphQLService.cs
In CryptoGraphQLService, update the
GetAssestsQuery
method with the following code:public async IAsyncEnumerable<IGetAssestsQuery_Assets_Nodes?> GetAssestsQuery([EnumeratorCancellation] CancellationToken token)
{
string? endCursor = null;
IGetAssestsQueryResult? queryResult;
do
{
var result = await _cryptoClient.GetAssestsQuery.ExecuteAsync(endCursor, token).ConfigureAwait(false); // Executes the GetAssestsQuery
result.EnsureNoErrors(); // Throws a GraphQLClientException if the GraphQL Server returns an error
queryResult = result.Data;
if (queryResult?.Assets?.Nodes is not null)
{
foreach (var node in queryResult.Assets.Nodes)
{
yield return node;
}
}
endCursor = queryResult?.Assets?.PageInfo?.EndCursor; // Upates the endCursor (used for pagination)
} while (queryResult?.Assets?.PageInfo?.HasNextPage is true); // Continues pagination until HasNextPage is false
}
3. Run the App + Verify Data
- In Visual Studio, build + deploy the Android app to the Android Emulator
- In the Android Emulator, on the Dashbaord page, verify data from the GraphQL Backend is now displayed
- On the Dashboard page, on the top cyrpto ticker, scroll right-to-left until the data for BTC is displayed
- On the Dashboard page, note the price of BTC
- In the Android Emulator, navigate to the Screener page
- On the Screener page, verify the price of BTC is incorect because the same data we hard-coded is displayed