Skip to content

Instantly share code, notes, and snippets.

@korniychuk
Created June 27, 2020 21:02
Show Gist options
  • Save korniychuk/53d6b97e8132d7ba59b27ec3c49d6353 to your computer and use it in GitHub Desktop.
Save korniychuk/53d6b97e8132d7ba59b27ec3c49d6353 to your computer and use it in GitHub Desktop.
Awaitable Observables :: Example 1
import { Component, OnInit } from '@angular/core';
interface Product { /* ... */ }
@Injectable()
class ProductApiService {
public async saveProduct(data: { product: Product; userId: number; pickUpTime: Date }): Promise<Product> {
// ...
}
}
@Component({ /* ... */ })
export class MyComponent implements OnInit {
public readonly currentUserId$: Observable<number> = this.store.select(fromStore.getCurrentUserId);
public readonly selectedPickUpTime$: Observable<Date> = this.store.select(fromStore.getSelectedPickUpTime);
public constructor(
private readonly store: Store<AppState>,
private readonly productApiService: ProductApiService,
private readonly dialogService: DialogServiceService,
) {}
public async saveWithRxJS(product: Product): Promise<void> {
combineLatest([this.currentUserId$, this.selectedPickUpTime$])
.pipe(
first(),
switchMap(([userId, pickUpTime]) => this.productApiService.saveProduct({ product, userId, pickUpTime })),
)
.subscribe(savedProduct => this.dialogService.savedSuccessful(product));
}
public async saveViaAsyncAwait(product: Product): Promise<void> {
const userId = await this.currentUserId$.pipe(first()).toPromise();
const pickUpTime = await this.selectedPickUpTime$.pipe(first()).toPromise();
const savedProduct = await this.productApiService.saveProduct({ product, userId, pickUpTime });
this.dialogService.savedSuccessful(savedProduct);
}
public async saveWithAwaitableObservables(product: Product): Promise<void> {
const userId = await this.currentUserId$;
const pickUpTime = await this.selectedPickUpTime$;
const savedProduct = await this.productApiService.saveProduct({ product, userId, pickUpTime });
this.dialogService.savedSuccessful(savedProduct);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment