Skip to content

Instantly share code, notes, and snippets.

View qmzik's full-sized avatar

Nikita Lebedev qmzik

  • Yekaterinburg, Russia
View GitHub Profile
@qmzik
qmzik / http.ts
Created August 12, 2019 09:47
Cancelling request with axios in Vue.js
import axios, { CancelTokenStatic } from 'axios';
export const http = axios.create({
baseURL: 'https://api.domen.com/',
});
const cancelToken: CancelTokenStatic = axios.CancelToken;
export let cancelSource = cancelToken.source();
export const refreshTokenForUpdateApp = (() => {
cancelSource = cancelToken.source();
import { Observable } from 'rxjs';
const source = new Observable<number>((subscriber) => {
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
subscriber.complete();
});
// Usage
/**
* A simple object with a `next` and `complete` callback on it.
*/
interface Observer<T> {
next: (value: T) => void;
complete: () => void;
}
/**
* A function that takes a simple object with callbacks
const source = function (subscriber: Observer<number>) {
subscriber.next(1);
subscriber.next(2);
subscriber.next(3);
subscriber.complete();
subscriber.next(4); // Упс, этого не должно быть
};
/**
* A class used to wrap a user-provided Observer. Since the
* observer is just a plain objects with a couple of callbacks on it,
* this type will wrap that to ensure `next` does nothing if called after
* `complete` has been called, and that nothing happens if `complete`
* is called more than once.
*/
class SafeSubscriber<T> {
closed = false;
class SafeSubscriber<T> {
closed = false;
constructor(private destination: Partial<Observer<T>>) {}
next(value: T) {
if (!this.closed) {
this.destination.next?.(value); // Note the ?. check here.
}
}
interface Observer<T> {
next: (value: T) => void;
complete: () => void;
error: (err: any) => void;
}
class SafeSubscriber<T> {
closed = false;
constructor(private destination: Partial<Observer<T>>) {}
next(value: T) {
if (!this.closed) {
this.destination.next?.(value);
}
}
const helloSocket = new Observable<string>((subscriber) => {
// Open a socket.
const socket = new WebSocket('wss://echo.websocket.org');
socket.onopen = () => {
// Once it's open, send some text.
socket.send('Hello, World!');
};
socket.onmessage = (e) => {
const source = (subscriber: Observer<string>) => {
const socket = new WebSocket('wss://echo.websocket.org');
socket.onopen = () => {
socket.send('Hello, World!');
};
socket.onmessage = (e) => {
subscriber.next(e.data);
};