首页 > 解决方案 > 如何在 Kotlin Andorid 中读取 Apollo 客户端响应/GraphQL 响应的响应数据

问题描述

我正在使用 Kotlin 开发一个 Android 应用程序。在我的应用程序中,我使用 Apollo Client 使用 GraphQL API。我现在要做的是我想检索响应的响应字段。

这是我的代码

protected fun _handleLoginButtonClick(view: View) {
        val apolloClient = ApolloClient.builder()
            .serverUrl("https://app.herokuapp.com/graphql")
            .okHttpClient(OkHttpClient())
            .build()
        val loginMutation = LoginMutation.builder()
            .identity(view.etf_email.text.toString())
            .password(view.etf_password.text.toString())
            .build()

        view.tv_login_error_message.text = "Started making request"
        apolloClient.mutate(loginMutation).enqueue(object: ApolloCall.Callback<LoginMutation.Data>() {
            override fun onFailure(e: ApolloException) {
                view.tv_login_error_message.text = e.message

            }

            override fun onResponse(response: Response<LoginMutation.Data>) {
                //here I dont know how to retrieve a field, accessToken
            }
        })
    }

正如您在 onResponse 回调中看到的注释,我不知道如何检索 accessToken 字段。我怎样才能找回它?

标签: androidkotlingraphqlapollo-client

解决方案


OnResponse 包含响应对象,它具有数据对象,您可以从中获取字段。

apolloClient.mutate(loginMutation).enqueue(object: ApolloCall.Callback<LoginMutation.Data>() { override fun onFailure(e: ApolloException) { view.tv_login_error_message.text = e.message

        }

        override fun onResponse(response: Response<LoginMutation.Data>) {
            //here you can use response to get your model data like accessToken
           response.data.(here you can get data from your model. eg accessToken)
        }
    })

推荐阅读