Ruegen
Ruegen

Reputation: 665

RXJS debounce and modify BehaviourSubject

I have this working however I'm unsure if this is the best way to go about it. I feel that there should be a simpler way in each of the methods - addTodo, deleteTodoById, updateTodo.

I am using BehaviourSubject to modify the array but as I update I was hoping to debounce user input (or delay) and update the localstorage in the background

How can improve and simplify the RXJS code?

import { Injectable } from "@angular/core"
import { Todo } from "./todo"
import { BehaviorSubject, Observable } from 'rxjs'
import { take } from 'rxjs/operators'


@Injectable()
export class TodoService {
  todos:  BehaviorSubject<Todo[]> = new BehaviorSubject<Todo[]>([]);
  observable: Observable<Todo[]> =  this.todos.asObservable();

  getTodos(): Observable<Todo[]> {
    try {
      const todos: Todo[] = JSON.parse(localStorage.getItem('todos'))
      if(!todos) {
        return this.todos
      }
      this.todos.pipe(take(1)).subscribe(() => {
        return this.todos.next(todos)
      })
      return this.todos;
    } catch(err) {
      console.log('have no local storage')
    }
  }

  addTodo(todo: Todo): TodoService {
    this.todos.pipe(take(1)).subscribe(todos => {
      this.updateLocalStorage([...todos, todo])
      return this.todos.next([...todos, todo])
    })
    return this
  }

  deleteTodoById(id): TodoService {
    this.todos.pipe(take(1)).subscribe(todos => {
      const filteredTodos = todos.filter(t => t.id !== id)
      this.updateLocalStorage(filteredTodos)
      return this.todos.next(filteredTodos)
    })
    return this
  }


  updateTodo(id, title): void {
    this.todos.pipe(take(1)).subscribe((todos) => {
      const todo = todos.find(t => t.id === id)
      if(todo) {
        todo.title = title
        const newTodos = todos.map(t => (t.id === id ? todo : t))
        this.updateLocalStorage(newTodos)
        return this.todos.next(newTodos)
      }
    })
  }

  updateLocalStorage(todos):void {
    this.todos.subscribe(t => {
      setTimeout(() => {
        localStorage.setItem('todos', JSON.stringify(todos))
      }, 300)
      })
  }
}

Upvotes: 1

Views: 1939

Answers (1)

Yanis-git
Yanis-git

Reputation: 7885

i am not sure about what you want to improve so far.

i have created this mooked application to show you how i manage this kind of operation.

On this application i have not use ReactiveFormModule from Angular which can easily abstract this part :

const inputElement = document.getElementById('input') as HTMLInputElement;
const onChange$ = fromEvent(
  inputElement, // In keyup from input field.
  'keyup'
).pipe(
  debounceTime(1000), // Delay the user input
  map(() => inputElement.value) // Transform KeyboardEvent to input value string.
);

By doing something like this

   <input
       type="text" 
       name="title"
       [formControl]="title"
   >

export class FooComponent implement OnInit {
    title: FormControl = new FormControl();
    ngOnInit() {
      this.title.valueChanges.pipe(debounceTime(1000)).subscribe(title => {
        // Do something with your debounced data.
      })
    }
}

Then you can follow this logic :

export class TodoService {
  private _todos$: BehaviorSubject<Todo[]>;
  private _todos: Todo[];

  constructor() {
      this._todos = (this.hasLocalStorage())?this.getLocalStorage():[];
      this._todos$ = new BehaviorSubject(this._todos);
  }

  add(todo: Todo) {
    this._todos.push(todo);
    this.refresh();
  }

  edit(id: number, title: string) {
    // Find by id and copy current todo.
    const todo = {
      ...this._todos.find(todo => todo.id === id)
    };
    // Update title
    todo.title = title;
    // Update todos reference
    this._todos = [
      // Find any other todos.
      ...this._todos.filter(todo => todo.id !== id),
      todo
    ];
    this.refresh();
  }

  get todos$(): Observable<Todo[]> {
    return this._todos$.asObservable();
  }
  private refresh() {
    this._todos$.next([...this._todos]);
    localStorage.setItem('todos', JSON.stringify(this._todos));
  }

  private hasLocalStorage(): boolean {
      return (localStorage.getItem('todos') !== null);
  }

  private getLocalStorage(): Todo[] {
    return JSON.parse(localStorage.getItem('todos'));
  }
}

1/ Here i have 2 properties, One is my store, where i will keep reference to my all todos, second is my BehaviorSubject which is used to notify rest of my application when my store are updated.

2/ On my constructor, i init both attributes by empty array or localStorage data (if present).

3/ I have refresh method which do 2 things, update my both properties.

4/ On add / Edit / Delete operation, i perform it as regular array operation, then i call 'refresh'.

voilà

live coding

Upvotes: 2

Related Questions