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:
private fun toggleTodoMutationCloud(todoId: Int, completeFlag: Boolean){// Init QuerytoggleTodoMutation = 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 UpdateNetwork.apolloClient.apolloStore().writeOptimisticUpdatesAndPublish(GetMyTodosQuery(), GetMyTodosQuery.Data(mutableListOf(todo)), UUID.randomUUID()).execute()getMyTodosQueryLocal()// Apollo runs query on background threadNetwork.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
- Build apps and APIs 10x faster
- Built-in authorization and caching
- 8x more performant than hand-rolled APIs