Is it possible to get rid of the BehaviourSubject to have an Observable with an initial value? Another thing I don't like is that I'm using getValue() and then modify this value and push it with next back to the Observable. Maybe there is a more elegant way to get the same thing?
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class UserProvider {
users$: Observable<{ id: string; name: string }[]>;
private usersSource: BehaviorSubject<{ id: string; name: string }[]>;
constructor() {
this.usersSource = new BehaviorSubject<any>([
{ id: '111', name: 'Jack' },
{ id: '222', name: 'John' },
{ id: '333', name: 'Foo' },
]);
this.users$ = this.usersSource.asObservable();
}
addUser(user: { id: string; name: string }) {
const currentUsers = this.usersSource.getValue();
currentUsers.push(user);
this.usersSource.next(currentUsers);
}
removeUser(userId: string) {
const currentUsers = this.usersSource.getValue();
const index = currentUsers.findIndex(user => user.id === userId);
if (index !== -1) {
if (this.selectedUserIdSource.getValue() === currentUsers[index].id) {
this.selectedUserIdSource.next(null);
}
currentUsers.splice(index, 1);
this.usersSource.next(currentUsers);
}
}
}
Subject
instead which do not require initial value \$\endgroup\$