Skip to content

Implement Optimistic Updates

Convertor Tuple Input Pattern

Mutations use a (Params, bool) tuple to optionally enable optimistic responses.

Mutation Request Convertor with Tuple Input

Section titled “Mutation Request Convertor with Tuple Input”
@riverpod
Convertor<GMutateAttendeeSaveReq, (UpsertRequestParams<GMutateAttendeeSaveVars>, bool)>
attendeeUpsertConvertor(Ref ref) {
return Convertor((params) {
final (requestParams, optimistic) = params;
return GMutateAttendeeSaveReq((builder) {
builder
..requestId = 'attendee_upsert_${requestParams.toString()}'
..vars = requestParams.vars.toBuilder();
if (optimistic) {
builder
..optimisticResponse.attendeeSave.id = '__optimistic__'
..optimisticResponse.attendeeSave.fullName =
requestParams.vars.attendeeArg?.fullName;
}
});
});
}
Stream<AttendeeModel> upsert({
required AttendeeUpsertInput input,
bool optimistic = true,
}) {
final vars = inputConvertor.execute(input);
return upsertDatasource
.thenMap(mutationModelConvertor)
.execute((UpsertRequestParams(vars: vars), optimistic));
}
  1. Optimistic = true: Ferry immediately updates cache with optimistic data
  2. Server responds: Ferry replaces optimistic entry with real data
  3. Error case: Ferry rolls back the optimistic update automatically