RxJS-- scheduler (Scheduler)

scheduler

What is the scheduler? The scheduler is when starting a subscription, control push notification. It consists of three parts.

  • Scheduling data structure. It knows how to run tasks in priority or other standards to store and queuing
  • An execution context scheduler. It indicates where tasks when executed (e.g., immediately or in the callback mechanism as in setTimeout or process.nextTick, and frame or animated)
  • The scheduler has a (virtual) timer. It is a concept of "time", by the scheduler process now(). Scheduled on a specific scheduler, it only follows the timer indicated.

The scheduler allows you to execute in the context of the definition of notification to push Observable observers

Here is an example, we use a simple push Observable to synchronize the values 1,2,3, and to use these values, using an operator observeOnto a particular asyncscheduler.

import { Observable, asyncScheduler } from 'rxjs';
import { observeOn } from 'rxjs/operators';

const observable = new Observable((observer) => {
    observer.next(1);
    observer.next(2);
    observer.next(3);
    observer.complete();
}).pipe(
    observeOn(asyncScheduler)
);

console.log('just before subscribe');
observable.subscribe({
    next(x) {
        console.log('got value ' + x)
    },
    error(err) {
        console.log('something wrong occurred: ' + err);
    },
    complete() {
        console.log('done');
    }
});
console.log('just after subscribe');

Execution of output:

just before subscribe
just after subscribe
got value 1
got value 2
got value 3
done

Note how the notification got value...is in just after subscribeafter being pushed, it is the default behavior difference with our previous very far. This is because observeOn(asyncScheduler)in new Observablebetween the observer and the introduction of a final proxy observer. Let's put before renaming some of the identification code and then look at:

import { Observable, asyncScheduler } from 'rxjs';
import { observeOn } from 'rxjs/operators';

var observable = new Observable((proxyObserver) => {
    proxyObserver.next(1);
    proxyObserver.next(2);
    proxyObserver.next(3);
    proxyObserver.complete();
}).pipe(
    observeOn(asyncScheduler)
);

var finalObserver = {
    next(x) {
        console.log('got value ' + x)
    },
    error(err) {
        console.error('something wrong occurred: ' + err);
    },
    complete() {
        console.log('done');
    }
};

console.log('just before subscribe');
observable.subscribe(finalObserver);
console.log('just after subscribe');

proxyObserverIn observeOn(asyncScheduler)the creation of the agency in the observer next(value)function probably like this:

const proxyObserver = {
    next(val) {
        asyncScheduler.schedule(
            (x) => finalObserver.next(x),
            0,  //延迟参数
            val //这个值是从上面的 x 传过来的
        );
    },
    // ...
}

the asyncscheduler operation can be used setTimeoutor setInterval, even if it is given delaythe value 0. Typically, in Javascript, setTimeout(fn, 0)we know how to run the first iteration of the loop function the next event fn.

The method scheduler schedule()has one parameter delay, which refers to time with respect to a digital scheduler own internal clock. A time scheduler need not have any associated actual time. This is a temporary operation as delaythe operator rather than as an actual value of the time, but time is determined by the scheduler clock. This is particularly useful in testing, it is this virtual time scheduler may be used in disguise real time, when the real time synchronization to run scheduled tasks.

Type scheduler

asyncThe scheduler is RsJS many built a scheduler schedulers. Each of them can be created and returned, by using the Schedulerobject's static properties.

SCHEDULER PURPOSE
null Do not pass any scheduler, and the notification is transmitted to synchronize a recursive manner. The time constant for the operator or operators tail recursion.
queueScheduler Framework of the current event queue scheduling (trampoline scheduler). With this iterative operations
asapScheduler Micro-scheduling the task queue, which queue using the same promises. Substantially after the current job, but before the next job. Asynchronous use this constraint
asyncScheduler By setIntervalscheduling work. In the time-based operations with this
animationFrameScheduler Scheduled Tasks will occur before the contents of a browser to redraw the next. It can be used to create a smooth animation browser

Use scheduler

You may use RsJS scheduler already in your code, without an explicit schedule type of instructions. This is because all of the concurrent processing Observable are optional operator scheduler. If you do not provide scheduler, RxJS will select a default scheduler by using the minimum concurrent principle. This means that the least complicated scheduler needs to select a safe operator. For example, a limited and small amount of return Observable operator, RxJS scheduler does not use, for example, nullor undefined. For a possible return to large or unlimited messaging, it will use queuethe scheduler. For operator time, it will use async.

Because RxJS using a minimum concurrent scheduler, you can choose a different schedulers, if you want to be introduced for the purpose of concurrent performance. To specify a particular scheduler, you can send those operators transfer scheduler method, e.g.from([10, 20, 30], asyncShceduler)

Creating operator Static schedulers will typically be passed as an argument. For example, from([10, 20, 30])allowing each of a push from when you arrayspecify a notification scheduler conversion. It is usually the last parameter on the operator. The following static creation operator a scheduler parameters are transmitted:

  • bindCallback
  • bindNodeCallback
  • combineLatest
  • concat
  • empty
  • from
  • fromPromise
  • interval
  • merge
  • of
  • range
  • throw
  • timer

The context of the call will subscribe () to use subscribeOnscheduling. subscribeObservable call will default, it will be synchronized and immediate way call. However, you may want to delay or given scheduler schedules the actual subscription, operator Example subscribeOn (scheduler), the inside scheduleris to provide you parameters.

Use observeOnnotifications to push the scheduling context. Like we have seen, examples of operators observeOn(scheduler)to introduce Observer intermediary between the source and target Observable observers, the mediator dispatcher given by your shcedulercall to the target viewer.

Examples operator passing as an argument a scheduler.

As time-dependent operators bufferTime, debounceTime, delay, sampleTime, throttleTime, timeInterval, timeout, timeoutWith, windowTimea scheduler parameters with all the last parameter, and other operators will be in default asyncScheduler.

Other examples of transmission scheduling parameters of the operator cacheas: combineLatest, concat, merge, expand, publishReplay, startWith, .

Notice cacheand publishReplayboth accept a retrieval device, because they use ReplaySubject. ReplaySubject constructor pass an optional scheduler as the last parameter, because the processing time can ReplaySubject, it will be meaningful only in the context of the scheduler. ReplaySubject the default queuescheduler provides a clock.

PS: RxJS series synchronized to https://github.com/MarsonShine/JavascriptStudy/tree/master/src/rxjs/docs

Guess you like

Origin www.cnblogs.com/ms27946/p/RxJS-Scheduler.html