为什么突变更改数据后ApolloQueryWatcher不触发?

时间:2019-07-07 10:49:56

标签: android graphql apollo apollo-android

在Apollo Android中遵循支持缓存之后 此处:Support For Cached Responses for Android

并且已经尝试离线查询,并且可以正常工作并且数据来自缓存

  • 打开应用程序后的第一种情况是使用“ MyApolloClinet”对象的查询来加载数据列表,该对象是从“ ApolloClient”继承的自定义类

  • 使用“ .watcher()。enqueueAndWatch()”方法获取数据后,使用新数据回调来自阿波罗的响应并更新recyclerView

  • 我选择要从查询数据列表中更新或“删除”记录的项目,以在缓存和数据库中进行更改。

  

我可以单击任何项​​目,然后显示一个对话框来编辑该项目的名称   记录项

通常使用Mutation发送更新的名称后,高速缓存已更改,数据库在线也已更改。

此处的问题:UI完全没有改变,因为.watcher()方法返回了ApolloQueryWatcher实例,该实例具有名为enqueueAndWatch的方法不会触发作为任何更改来监听,以使用该记录的新更改值更新UI和列表

以下是我的代码中的一些摘要, 我正在使用Kotlin和Java。

  • 使用查询从数据库获取用户数据的方法

    fun getAllUsers() {
    progress.visibility = VISIBLE
    MyApolloClient.getApolloClient(this).query(GetUsersWithPagesQuery.builder().build())
        .watcher().enqueueAndWatch(object : MyApolloClient.MyCallBack<GetUsersWithPagesQuery.Data>(this) {
            override fun onResponseUI(response: Response<GetUsersWithPagesQuery.Data>) {
                progress.visibility = GONE
                if (response.data() != null) {
                    reachBottom = false
                    users.clear()
                    for (i in response.data()!!.users()) {
                        val u = GetUsersWithPagesQuery.Data1("", i.id(), i.name(), i.email())
                        users.add(u)
                    }
                    adapter.notifyDataSetChanged()
    
                }
            }
    
            override fun onFailureUI(response: ApolloException) {
    
            }
        })
    

    }

  • 自定义回调以在UI中使用响应

    public static abstract class MyCallBack<T> extends ApolloCall.Callback<T> {
    
    Activity activity;
    
    public MyCallBack(Activity activity) {
        this.activity = activity;
    }
    
    @Override
    public void onResponse(@NotNull com.apollographql.apollo.api.Response<T> response) {
        activity.runOnUiThread(() -> onResponseUI(response));
    
    }
    
    public abstract void onResponseUI(@NotNull com.apollographql.apollo.api.Response<T> response);
    
    public abstract void onFailureUI(@NotNull ApolloException response);
    
    @Override
    public void onFailure(@NotNull ApolloException e) {
        activity.runOnUiThread(() -> onFailureUI(e));
    }
    

    }

  • 获取具有缓存支持的Apollo Client对象

    public static ApolloClient getApolloClient(Context context) {
    
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.addNetworkInterceptor(httpLoggingInterceptor);
    builder.addNetworkInterceptor(chain -> {
        Request original = chain.request();
        Request.Builder builder1 = original.newBuilder().method(original.method(), original.body());
        builder1.header("Authorization", "Bearer " + PrefManager.getInstance(context).getAPIToken());
        return chain.proceed(builder1.build());
    });
    OkHttpClient okHttpClient = builder.build();
    //Directory where cached responses will be stored
    File file = new File(context.getApplicationContext().getFilesDir(), "apolloCache");
    
    //Size in bytes of the cache
    long size = 1024 * 1024;
    
    //Create the http response cache store
    DiskLruHttpCacheStore cacheStore = new DiskLruHttpCacheStore(file, size);
    
    ApolloSqlHelper apolloSqlHelper = ApolloSqlHelper.create(context, "zari");
    
    //Create NormalizedCacheFactory
    NormalizedCacheFactory cacheFactory = new SqlNormalizedCacheFactory(apolloSqlHelper);
    
    //Create the cache key resolver, this example works well when all types have globally unique ids.
    CacheKeyResolver resolver = new CacheKeyResolver() {
        @NotNull
        @Override
        public CacheKey fromFieldRecordSet(@NotNull ResponseField field, @NotNull Map<String, Object> recordSet) {
            return formatCacheKey((String) recordSet.get("id"));
        }
    
        @NotNull
        @Override
        public CacheKey fromFieldArguments(@NotNull ResponseField field, @NotNull Operation.Variables variables) {
            return formatCacheKey((String) field.resolveArgument("id", variables));
        }
    
        private CacheKey formatCacheKey(String id) {
            if (id == null || id.isEmpty()) {
                return CacheKey.NO_KEY;
            } else {
                return CacheKey.from(id);
            }
        }
    };
    
    apolloClient = ApolloClient.builder()
            .serverUrl(url)
            //.httpCache(new ApolloHttpCache(cacheStore))
            .normalizedCache(cacheFactory, resolver)
            .okHttpClient(okHttpClient)
            .build();
    return apolloClient;
    

    }

  • 带有编辑文本的警报对话框,以从Recycler Adapter中的列表更新项目

    builder.setPositiveButton("Change", (dialog, which) -> {
        if (!n.isEmpty())
            MyApolloClient.getApolloClient(activity).mutate(UpdateUserMutation.builder().id(user
                    .id()).name(n).build()).enqueue(new MyApolloClient.MyCallBack<UpdateUserMutation.Data>(activity) {
                @Override
                public void onResponseUI(@NotNull Response<UpdateUserMutation.Data> response) {
                    if (response.errors() != null && response.errors().size() > 0) {
                        StaticMembers.toastMessageShort(activity, response.errors().get(0).message());
                    } else {
                        StaticMembers.toastMessageShort(activity, response.data().updateUser().name() + " updated");
                    }
                }
    
                @Override
                public void onFailureUI(@NotNull ApolloException response) {
    
                }
            });
    
    });
    

那么,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

Apollo-android无法知道您的突变将要修改的节点。如果您的API允许,您可以查询新用户作为突变产生的返回数据,以强制更新缓存。

或者,如果请求成功,您可以手动修改缓存,但这似乎涉及更多。