标签: reactive-programming

Reactive Framework for .NET示例证明了它的用处

围绕.NET 4.0中的新Reactive Framework进行了大量宣传.虽然我认为我不知道它的基本概念,但我并没有完全销售,因此它非常有用.你能想出一个很好的例子(中途易于理解),它完全展示了Rx的力量和实用性吗?展示一些使用Rx完成生活变得更容易的东西.

.net reactive-programming system.reactive

9
推荐指数
1
解决办法
1617
查看次数

如何从ReactiveCocoa信号中获取"旧值"?

如果我像这样使用RACable:

[RACAbleWithStart(self.myProp) subscribeNext:^(id x) {
   // Do stuff

}];
Run Code Online (Sandbox Code Playgroud)

如何才能访问myProp的旧值(在更改之前导致信号触发)?所以我可以像这样访问它:

[RACAbleWithStart(self.myProp) subscribeNext:^(id x) {
   // Do stuff
   id newValue = x;
   id oldValue = RAC_oldValue;
}];
Run Code Online (Sandbox Code Playgroud)

objective-c key-value-observing reactive-programming ios reactive-cocoa

9
推荐指数
1
解决办法
2980
查看次数

如何使用Observable实现轮询?

我有一个参数化的休息调用应该每隔五秒用不同的参数执行:

Observable<TResult> restCall = api.method1(param1);
Run Code Online (Sandbox Code Playgroud)

我需要创建一个Observable<TResult>将每隔5秒轮询一次restCall ,其中包含param1的不同值.如果api调用失败,我需要收到错误并在5秒内进行下一次调用.只有在restCall完成(成功/错误)时才应测量调用之间的间隔.

我目前正在使用RxJava,但.NET示例也会很好.

c# reactive-programming system.reactive async-await rx-java

9
推荐指数
1
解决办法
3129
查看次数

Rx后退并重试

这基于此SO中提供的代码:编写Rx"RetryAfter"扩展方法

我正在使用Markus Olsson的代码(目前仅进行评估),之前有人要求我试图在Github上抓住Markus,但是在我工作的地方被阻止了,所以我觉得我唯一能做的就是问在这里.很抱歉,如果这与任何人都很糟糕.

所以我在一个小的演示中使用以下代码:

class Attempt1
{
    private static bool shouldThrow = true;

    static void Main(string[] args)
    {
        Generate().RetryWithBackoffStrategy(3,
               MyRxExtensions.ExponentialBackoff,
            ex =>
            {
                return ex is NullReferenceException;
            }, Scheduler.TaskPool)
            .Subscribe(
                OnNext,
                OnError
            );

        Console.ReadLine();
    }

    private static void OnNext(int val)
    {
        Console.WriteLine("subscriber value is {0} which was seen on threadId:{1}",
            val, Thread.CurrentThread.ManagedThreadId);
    }

    private static void OnError(Exception ex)
    {
        Console.WriteLine("subscriber bad {0}, which was seen on threadId:{1}",
            ex.GetType(),
            Thread.CurrentThread.ManagedThreadId);
    }

    static IObservable<int> Generate()
    {
        return Observable.Create<int>(
            o =>
            { …
Run Code Online (Sandbox Code Playgroud)

c# reactive-programming system.reactive

9
推荐指数
2
解决办法
2990
查看次数

Rx TaskPoolScheduler vs EventLoopScheduler,内存使用情况

我正在尝试对众多独立数据源进行POC.经典观察者风格应用的排序.数据馈送的数量可能从几百到几千不等,观察者的数量可能会有所不同,从2到20000.以下是简单数据馈送可观察模型的快速示例:

    public class FeedMockUp
    {
        private readonly IScheduler observerScheduler;
        private readonly Random rnd = new Random((int)DateTime.Now.Ticks);

        private readonly Subject<double> sourceObservable;
        private readonly IObservable<double> testedObservable;

        public FeedMockUp(IScheduler observerScheduler)
        {
            this.observerScheduler = observerScheduler;
            sourceObservable = new Subject<double>();

            testedObservable =
                Observable.Create<double>(x =>
                {
                    var underlyingSourceDisposable =
                        sourceObservable
                            .Subscribe(_ => x.OnNext(rnd.NextDouble()));
                    return underlyingSourceDisposable;
                });
        }

        public IDisposable SubscribeToUnderlyingFeed(int numberOfSubscribers)
        {
            int counter = 0;
            var disposable = new CompositeDisposable();

            for (int i = 0; i < numberOfSubscribers; i++)
            {
                disposable.Add(testedObservable
                    .ObserveOn(observerScheduler)
                    .Subscribe(_ => Interlocked.Increment(ref …
Run Code Online (Sandbox Code Playgroud)

reactive-programming system.reactive c#-4.0

9
推荐指数
2
解决办法
3699
查看次数

RxJs:如何基于observable的状态循环?

我试图让RxJs循环遍历我的流中的Observable,直到它处于某种状态,然后让流继续.具体来说,我正在将同步do/while循环转换为RxJs,但我假设同样的答案也可以用于for或while循环.

我认为我可以使用doWhile(),但似乎条件函数无法访问流中的项目,这似乎打败了我的目的.

我不完全确定正确的反应术语对于我想要的是什么,但这里有一个我想要的例子:

var source = new Rx.Observable.of({val: 0, counter: 3});

source.map(o => {
  o.counter--;
  console.log('Counter: ' + o.counter);

  if (!o.counter) {
    o.val = "YESS!";
  }
  return o;
})
.doWhile(o => { 
  return o.counter > 0; 
})
.subscribe(
    function (x) {
        console.log('Next: ' + x.val);
    },
    function (err) {
        console.log('Error: ' + err);   
    },
    function () {
        console.log('Completed');   
    });
Run Code Online (Sandbox Code Playgroud)

预期的产出是:

Counter: 3
Counter: 2
Counter: 1
Counter: 0
Next: YESS!
Completed
Run Code Online (Sandbox Code Playgroud)

假设这是一个可解决的问题,我不清楚如何标记循环时想要返回的"开始".

javascript reactive-programming rxjs

9
推荐指数
2
解决办法
1万
查看次数

如何用Angular2和Reactive听一下css动画师的结尾

我想在我的Angular2应用程序中手动执行页面转换.所以我到目前为止所做的是产生了一个服务,我从一个处理导航的组件调用.当您单击某个链接,图标或我称之为AnimationService goTo方法的任何内容时.这将接收一个URL并推送到Observable流/主题.这是迄今为止的服务:

@Injectable()
export class AnimationService {
    // should you be a directive?
    animationStream: Subject<string> = new Subject<string>();
    animationStreamEnd:Subject<string> = new Subject<string>()

    constructor() {

        // this is to listen for when it is time to navigate to whereever? 
        this.animationStreamEnd.subscribe(resp => {
            // redirect the url / app here
            this.router.go(resp);
        });

    }

    goTo(url:string): void {
        // so, broadcast down to trigger the css animation...
        this.animationStream.next(url);
    }

}
Run Code Online (Sandbox Code Playgroud)

我希望动画的内容ngClass在它的HTML模板中有一个条件,就像这样[ngClass]="{'animate-left': applyTransitionClass}",它看起来像这样

<div class="gridClass" [ngClass]="{'animate-left': applyTransitionClass}">
    <div class="gridRow">
        <route-view></route-view> …
Run Code Online (Sandbox Code Playgroud)

reactive-programming css-animations typescript angular

9
推荐指数
2
解决办法
4500
查看次数

在返回订阅服务器之前,如何拦截可观察对象并在RxJava中修改它?

我正在尝试命中一个服务并返回一个对象列表,在它返回给订阅者之前,我想对列表中的每个对象进行另一个同步调用,以进行另一个服务调用来设置一个丢失的字段.我已成功完成所有调用,但订阅者返回的对象具有此字段,我需要将其设置为null.这是我的代码示例:

示例服务:

rx.Observable<List<ExampleObject>> getExampleObject();
rx.Observable<MissingObject> getMissingObjectByFoo(@Path("foo") String foo);
Run Code Online (Sandbox Code Playgroud)

示例类:

public class ExampleObject {
    String foo;
    MissingObject bar;

    public String getFoo() {
        return this.foo;
    }

    public void setFoo(String value) {
        this.foo = value;
    }

    public MissingObject getBar() {
        return this.bar;
    }

    public void setBar(MissingObject value) {
        this.bar = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

示例实施:

mService.getExampleObject().flatMap(new Func1<List<ExampleObject>, Observable<?>>() {
            @Override
            public Observable<List<ExampleObject>> call(List<ExampleObject> exampleObjects) {
                for (ExampleObject entry : exampleObjects) {
                    String foo = entry.getFoo();
                    mService.getMissingObjectByFoo(foo)
                            .subscribeOn(mScheduler.backgroundThread())
                            .observeOn(mScheduler.mainThread())
                            .subscribe(new Subscriber<MissingObject>() {
                        @Override
                        public void …
Run Code Online (Sandbox Code Playgroud)

java android reactive-programming rx-java retrofit

9
推荐指数
1
解决办法
2026
查看次数

RXJS while循环用于分页

我尝试从swap api查询所有人的数据.URL swapi.co/api/people返回一个带有人员数组和URL(swapi.co/api/people/?page=2)的对象,我从中获取下一个数据.我想要做的是订阅方法每次新页面可用时更新角度组件.

我是反应式编程模型的新手.如何实现while循环或一系列Observable?

这适用于第一页:

getAllPeople(): Observable<Person[]> {
    let nextUrl = http://swapi.co/api;

    let source = Observable.create(observer => {

            this.http.get(nextUrl, { headers: this.headers })
            .map(response => {
                    let body = response.json();
                    nextUrl = body.next;
                    return nextUrl != null ? body.results as Person[] : null;
                }
            )
            .retry(5)//send same request based on the url of the previous request till the field next is null
            .catch(error => observer.error(error))
            .subscribe(persons => {
                    if (persons !== null) {
                        observer.next(persons)
                    }
                }
            );

        //observer.complete(); …
Run Code Online (Sandbox Code Playgroud)

javascript reactive-programming rxjs angularjs typescript

9
推荐指数
1
解决办法
2690
查看次数

在使用Flux(包括重试)消耗时按顺序调用非阻塞操作

因此,我的用例是在使用Project Reactor以反应式样式编程时使用Spring Webflux应用程序中的Kafka消息,并按照从Kafka收到消息的相同顺序对每个消息执行非阻塞操作.系统也应该能够自行恢复.

以下是设置为使用的代码段:

    Flux<ReceiverRecord<Integer, DataDocument>> messages = Flux.defer(() -> {
        KafkaReceiver<Integer, DataDocument> receiver = KafkaReceiver.create(options);
        return receiver.receive();
    });

    messages.map(this::transformToOutputFormat)
            .map(this::performAction)
            .flatMapSequential(receiverRecordMono -> receiverRecordMono)
            .doOnNext(record -> record.receiverOffset().acknowledge())
            .doOnError(error -> logger.error("Error receiving record", error))
            .retryBackoff(100, Duration.ofSeconds(5), Duration.ofMinutes(5))
            .subscribe();
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我所做的是:从Kafka获取消息,将其转换为用于新目标的对象,然后将其发送到目标,然后确认偏移以将消息标记为已消耗和处理.以与从Kafka消耗的消息相同的顺序确认偏移量是至关重要的,这样我们就不会将偏移量移动到未完全处理的消息之外(包括将一些数据发送到目的地).因此我用a flatMapSequential来确保这一点.

为简单起见,我们假设该transformToOutputFormat()方法是一种身份变换.

public ReceiverRecord<Integer, DataDocument> transformToOutputFormat(ReceiverRecord<Integer, DataDocument> record) {
    return record;
}
Run Code Online (Sandbox Code Playgroud)

该performAction()方法需要通过网络执行某些操作,例如调用HTTP REST API.因此适当的API返回Mono,这意味着需要订阅链.此外,我需要ReceiverRecord通过此方法返回,以便可以在上面的flatMapSequential()运算符中确认偏移量.因为我需要Mono订阅,我正在flatMapSequential上面使用.如果没有,我可以用一个map代替.

public Mono<ReceiverRecord<Integer, DataDocument>> performAction(ReceiverRecord<Integer, DataDocument> record) {
    return Mono.just(record)
            .flatMap(receiverRecord ->
                    HttpClient.create()
                            .port(3000)
                            .get()
                            .uri("/makeCall?data=" + …
Run Code Online (Sandbox Code Playgroud)

java reactive-programming apache-kafka project-reactor spring-webflux

9
推荐指数
1
解决办法
1295
查看次数