How would you implement optimistic updates in RxJS? See this example:
const todoIdSource: Subject<string> = new Subject();
const $todo = todoIdSource.pipe(
tap(id => {
const optimisticTodo: any = {
userId: 1,
id: id, // Use some value from the source observable
title: "delectus aut autem",
completed: false
};
// TODO force emit optimisticTodo! How? :)
}),
concatMap((id) => ajax('https://jsonplaceholder.typicode.com/todos/' + id)),
map(response => response.response)
);
$todo.subscribe(value => console.log('TODO', value));
todoIdSource.next('1');
$todo does not emit until the ajax call completed.
But I want it to emit immediately the optimistic value as soon as todoIdSource emits.
In the end $todo should have emitted 2 values:
- the optimistic value
- the value from ajax result
Note:
- The optimistic value should not trigger the ajax call.
- The optimistic value should be able to use data from the source observable
todoIdSource.
Is there an elegant way to accomplish that in RxJS? I could imagine to introduce a second Observable optimisticTodo$ and then merge it with $todo. But that does not feel elegant :)