Shopify / mobile-buy-sdk-android

Shopify’s Mobile Buy SDK makes it simple to sell physical products inside your mobile app. With a few lines of code, you can connect your app with the Shopify platform and let your users buy your products using their credit card.
MIT License
212 stars 136 forks source link

How to asynchronously wait the query result #687

Open blob84 opened 3 years ago

blob84 commented 3 years ago

Hello this is the code to make a query:

GraphClient client = ...;

...

Storefront.QueryRootQuery query = Storefront.query(rootQuery -> rootQuery
  .shop(shopQuery -> shopQuery
    .name()
    .currencyCode()
    .refundPolicy(refundPolicyQuery -> refundPolicyQuery
      .title()
      .url()
    )
  )
);

client.queryGraph(query).enqueue(new GraphCall.Callback<Storefront.QueryRoot>() {

  @Override public void onResponse(@NonNull GraphResponse<Storefront.QueryRoot> response) {
    String name = response.data().getShop().getName();
    String currencyCode = response.data().getShop().getCurrencyCode().toString();
    String refundPolicyUrl = response.data().getShop().getRefundPolicy().getUrl();
  }

  ...
});

I need that the processed data in the onResponse method should be available outside it. I need to wait (non-blocking) these data and use them in the future elsewhere.

I tried with CompletabeFuture but I get the Storefront.QueryRoot memory address:

        CompletableFuture<GraphResponse> completableFuture
                = CompletableFuture.supplyAsync(() -> {
            try {
                return call.execute();
            } catch (GraphError graphError) {
                graphError.printStackTrace();
                return null;
            }
        });

        CompletableFuture<String> future = completableFuture
                .thenApply(response ->  response.data().toString());

        try {
            responseData = future.get();

        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
blob84 commented 3 years ago

I forgot the type GraphResponse<Storefront.QueryRoot>. It works with CompletableFuture. If I run the code without CompletableFuture I get error:

       try {
            GraphResponse<Storefront.QueryRoot> gresponse =  call.execute();
           responseData = gresponse.data().getShop().getName();
        } catch (GraphError graphError) {
            System.out.println("hello qui");
            graphError.printStackTrace();
        }

error: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.domain.shopifyapp/com.domain.shopifyapp.MainActivity}: android.os.NetworkOnMainThreadException

Let me know if there is a solution better than CompletableFuture . Thanks.