简体   繁体   中英

Reactive ObjC emit sequence with time interval

I am trying to emit a sequence of numbers with a delay between each emission. I have a NSIndexSet with a series of numbers,

[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 100)]

Now I want to emit each number with a delay,Like emit number 2 few seconds after emitting number 1 and so on. I am new to Reactive ObjC. How can I do this?

I am trying something like this,

[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, runescapePackages.count-1)].rac_sequence ...

Basically I want to emit each item from a background thread and the Subscriber consumes that item in Main Thread.

How to do it in OBJ-C?

There's no built-in operator that does this right away, but it is not too hard to construct by yourself.

You can turn your sequence into a RACSignal via [sequence signal . Also, you can provide a scheduler right there if you want (if not, RAC will create a new scheduler for you)

RACScheduler *backgroundScheduler = [RACScheduler scheduler];
RACSignal *sequence = [[[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 50)]
                                    rac_sequence]
                                   signalWithScheduler:backgroundScheduler];

The problem with this signal is, that it emits all values of the sequence right away. Maybe you have tried the delay operation yourself already, but that does not help since it delays all events by the same amount, so they arrive delayed, but still right after each other.

The basic idea to solve this is to paire the number signal with a regular tick.

Here's how you can create a signal that emits events at regular intervals

RACSignal *tick = [RACSignal interval:0.5 onScheduler:backgroundScheduler];

Now in order to "pair them up" you want to use the zip operator, because that waits until both signals have sent their first value until it sends a tuple with both values as its first value, then waits until both sent their second value and so on. Thus, the number values of the sequence have to wait up for their tick events

[[[[RACSignal zip:@[tick, sequence]] map:^(RACTuple *tuple) {
    return [tuple second];
}] deliverOn:[RACScheduler mainThreadScheduler]]
 subscribeNext:^(id  _Nullable x) {
    NSLog(@"Value: %@", x);
}];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM