How to remove observer using ReactiveCocoa?

How to stop receiving a new name after an event?

[RACObserve(self, username) subscribeNext:^(NSString *newName) { if ([newName isEqualToString:@"SomeString"]) { //Do not observe any more } }]; 

PS Sorry for the obvious question, but I can not find the answer.

+6
source share
2 answers

In ReactiveCocoa, itโ€™s important to think a little about things: you donโ€™t want to โ€œremoveโ€ the observer, you want to create a signal that ends when something happens.

You can use takeUntilBlock: to receive a signal that stops sending values โ€‹โ€‹after a certain time:

 [[RACObserve(self, username) takeUntilBlock:^(NSString *name) { return [name isEqualToString:@"something"]; }] subscribeNext:^(NSString *name) { NSLog(@"%@", name); }]; 

But this will not send the next line @"something" , but only the names before it. If necessary, you can add it:

 NSString *sentinel = @"something"; [[[RACObserve(self, username) takeUntilBlock:^(NSString *name) { return [name isEqualToString:sentinel]; }] concat:[RACSignal return:sentinel]] subscribeNext:^(NSString *name) { NSLog(@"%@", name); }]; 

It's not very elegant, but you could make a takeUntilBlockInclusive to help you with this and hide the rudeness there.

+9
source

You can use the "dispose" method of the RACDisposable object, which is returned from "subscribeNext".

 __block RACDisposable *handler = [RACObserve(self, username) subscribeNext:^(NSString *newName) { if ([newName isEqualToString:@"SomeString"]) { //Do not observe any more [handler dispose] } }]; 
+8
source

Source: https://habr.com/ru/post/985200/


All Articles