RxJava的平均值

时间:2015-04-17 05:51:24

标签: reactive-programming rx-java

我正在尝试使用Rx创建系统资源监视器。我使用一个observable线程,它每1000毫秒返回一次CPU使用率。现在我希望我的订阅者每10秒找到一次CPU使用率的平均值。

    public class seperate {
    private ScheduledThreadPoolExecutor executorPool;
    public void test()
   {

    Observable<Double> myObservable = Observable.create(
            new Observable.OnSubscribe<Double>() {
                @Override
                public void call(Subscriber<? super Double> sub) {
                    executorPool = new ScheduledThreadPoolExecutor(9);
                    int timeout1 = 10;
                    TimerTask timeoutTimertask1=new MyTimerTasks(sub);
                    executorPool.scheduleAtFixedRate(timeoutTimertask1,timeout1, timeout1,
                        TimeUnit.MILLISECONDS);
                    // This returns the cpu usage every 10ms.                      

                }
            }
        );
    Subscriber<Double> mySubscriber = new Subscriber<Double>() {
        @Override
        public void onNext(Double s) { System.out.println(s); }

        @Override
        public void onCompleted() { }

        @Override
        public void onError(Throwable e) { }
    };
    myObservable.subscribe(mySubscriber);

}

}

2 个答案:

答案 0 :(得分:3)

您可以使用bufferwindow将源排放分成多组项目,然后计算每组的average

Avarage是rxjava-math库的一部分。

此外,您可以使用interval简化代码。

以下是使用窗口和间隔的示例:

Observable myObservable = Observable.interval(10, TimeUnit.MILLISECONDS)
           .map(new Func1<Long, Double>() {                    
                @Override
                public Double call(Long aLong) {
                    Double d = 100.;//calculate CPU usage                             
                    return d;
                }
            })
            .window(10, TimeUnit.SECONDS)
            .flatMap(new Func1<Observable<Double>, Observable<Double>>() {
                @Override
                public Observable<Double> call(Observable<Double> windowObservable) {
                    return MathObservable.averageDouble(windowObservable);
                }
            });

答案 1 :(得分:1)

像这样使用MathObservable:

MathObservable.averageLong(longsObservable).subscribe(average -> Timber.d("average:%d", average));

更多信息可以在这里找到: https://github.com/ReactiveX/RxJava/wiki/Mathematical-and-Aggregate-Operators

源代码: https://github.com/ReactiveX/RxJavaMath