Mutation and update cache

Now let's do the integration part. Open TaskFragment.kt and add the following code at the bottom of the file:

githubTaskFragment.kt
private fun toggleTodoMutationCloud(todoId: Int, completeFlag: Boolean){
// Init Query
toggleTodoMutation = ToggleTodoMutation.builder().id(todoId).isCompleted(completeFlag).build()
getMyTodosQuery = GetMyTodosQuery.builder().build()
val index = listItems?.indexOfFirst { todo -> todo.id() == todoId}
var todos = listItems?.toMutableList()?.get(index!!)
val todo = GetMyTodosQuery.Todo(
todos?.__typename()!!,
todos.id(),
todos.title(),
todos.created_at(),
completeFlag)
var updatedList = listItems?.toMutableList()
updatedList?.set(index!!, todo)
// Optimistic Update
Network.apolloClient
.apolloStore()
.writeOptimisticUpdatesAndPublish(GetMyTodosQuery(), GetMyTodosQuery.Data(mutableListOf(todo)), UUID.randomUUID()).execute()
getMyTodosQueryLocal()
// Apollo runs query on background thread
Network.apolloClient.mutate(toggleTodoMutation)?.enqueue(object : ApolloCall.Callback<ToggleTodoMutation.Data>() {
override fun onFailure(error: ApolloException) {
Log.d("Todo", error.toString() )
}
override fun onResponse(@NotNull response: Response<ToggleTodoMutation.Data>) {
Network.apolloClient.apolloStore().write(toggleTodoMutation, response.data()!!)
getMyTodosQueryLocal()
}
})
}

We are making an optimistic update to the the apolloClient.apolloStore() and then doing the actual mutation over the cloud. Lets add this in our updateTaskCompleteStatus action handler,

override fun updateTaskCompleteStatus(taskId: Int, completeFlag: Boolean) {
- // Todo : Method for updating the complete status for the task
+ toggleTodoMutationCloud(taskId, completeFlag)
}

We already have the getMyTodosQueryLocal which queries the data from local cache and updates the list.

Did you find this page helpful?
Start with GraphQL on Hasura for Free
  • ArrowBuild apps and APIs 10x faster
  • ArrowBuilt-in authorization and caching
  • Arrow8x more performant than hand-rolled APIs
Promo
footer illustration
Brand logo
© 2024 Hasura Inc. All rights reserved
Github
Titter
Discord
Facebook
Instagram
Youtube
Linkedin
graphql-handbook