Reactivecocoa code Practice-More thinking _android

Source: Internet
Author: User

Related reading:

Reactivecocoa Code Practice-UI Component's RAC signal operation

Reactivecocoa Code Practice-RAC Network Request reconfiguration

1. Racobserve () The difference of macro-parameter writing

Previously written code considered the difference between racobserve (Self.timelabel, text) and Racobserve (self, timelabel.text). Because both of these methods observe the properties of the Self.timeLabel.text, and all of them can implement the function. An estimate is one of the authors ' original use. Later, it also provides support for the other, what is the difference between what is better?

Click to see Racobserve source code are mostly method calls, a layer of point in the end came to this method.

 
 

This method divides the keypath behind the comma by "." Into an array. and get three properties

BOOL keypathhasonecomponent = (Keypathcomponents.count = =);
NSString *keypathhead = keypathcomponents[];

This will take you to the head of the Keypatch and the part that goes around, and will call itself within the method below.

Adds the callback block to the remaining path components on the value. Also
//Adds the logic to the callbacks to the firstcomponentdisposable.
void (^addobservertovalue) (nsobject *) = ^ (NSObject *value) {
racdisposable *observerdisposable = [Value rac_ Observekeypath:keypathtail Options: (Options & ~nskeyvalueobservingoptioninitial) Observer:weakobserver block: Block];
[Firstcomponentdisposable () adddisposable:observerdisposable];

And the Keypathtail as Keypatch passed in, is recursive call, every time come in will cut off the first element, until bool keypathhasonecomponent this value equals Yes. Looking at this in terms of racobserve (self, timelabel.text) will trigger a recursive call, which is less performance than Racobserve (Self.timeLabel.text).

2. Set operation

Suppose there is a need now, there is a string of cipher array, we judge the password length is less than 6 bits is too short, will be thrown inside the system a message: xxx password is too short unqualified. The use of RAC is more convenient than conventional writing, one filters a custom and then returns directly.

Nsarray *pwds = @[@ "", @ "", @ "", @ ""];
Racsequence *results = [[Pwds.rac_sequence
filter:^ BOOL (NSString *pwd) {return
pwd.length <
}] Map:^id (NSString *pwd) {return
[pwd mutablecopy]stringbyappendingstring:@ "password too Short unqualified"];

The block code for the intermediate filter method executes only if the code executes below Results.array, which is equivalent to having a subscriber to execute. This is much like racsignal, because signal and sequence are streams, they share many of the same methods signal is the push-driven stream,sequence is the pull-driven stream.

You can also use the following method if you are removing other properties from the Racsequence object

Racsequence *s = [racsequence sequencewithheadblock:^id{return
@ Custom action;
} tailblock:^racsequence *{
return [racsequence new];
NSLog (@ "%@", S.head);

The two blocks are executed when the specified attribute is invoked, noting that the head is the first element of sequence, and tail is the remainder of the first element, so it is a sequence. (Dong Platinum ran blog park)

3. Signal Realization Game Skill Release

Suppose you now need to use RAC to simulate a method of exploding gas in an arcade. Press the specified button in the order that the front fist will release the ACE.

First you need to connect each button and set a signal to listen for all the keys to the set of individual signals to capture the title of each button.

Combine the signal of six keys with
racsignal *combosignal = [[racsignal merge:@[
[self.topbtn rac_signalforcontrolevents: UIControlEventTouchUpInside],
[self.bottombtn rac_signalforcontrolevents:uicontroleventtouchupinside],
[Self.leftbtn Rac_signalforcontrolevents:uicontroleventtouchupinside],
[self.rightbtn rac_ Signalforcontrolevents:uicontroleventtouchupinside],
[self. Bbtn Rac_signalforcontrolevents:uicontroleventtouchupinside],
[self. ABTN Rac_signalforcontrolevents:uicontroleventtouchupinside]]]
map:^id (UIButton *btn) {
return Btn.currenttitle;

Then the signal source for the buffer operation, every three seconds received all the key information captured, and to make judgments and subsequent operations

Set trigger gas condition
nsstring *combocode = @ "Next front fist";
Actual operation
racsignal *canaction = [[[Combosignal Bufferwithtime:onscheduler:[racscheduler Mainthreadscheduler]] Map: ^id (Ractuple *value) {return
[[value allobjects] componentsjoinedbystring:@ '];
}] Map:^id (NSString *value) { return
@ ([value containsstring:combocode]);
Call Combo: Method is skill release

The above code can achieve the expected function, as long as you can press out the specified key in three seconds buffer can release. But there is also a problem with this approach: set Buffer3 seconds after this block inside every three seconds will come once, that is, if you are in 0.5 seconds to press out the skills, it also needs to wait 2.5 seconds to release skills, obviously this is not acceptable in combat.

Then tried the other realization thought, tried takelast: and Takeuntilblock: and Scanwithstart: And other methods are not very appropriate, and finally used Aggregatewithstart: to achieve the purpose of the demand.

Set trigger gas condition
nsstring *combocode = @ "Next front fist";
Actual operation
_time = [[[NSDate alloc] init] timeIntervalSince1970];
[[Combosignal aggregatewithstart:@ "" Reduce:^id (nsstring* running, nsstring* next) {
if ([[[[NSDate alloc] init] TIMEINTERVALSINCE1970]-_time) < 3) {
NSString *str = [NSString stringwithformat:@ "%@%@", Running,next];
return [str containsstring:combocode]? [Self combo]:str;
}
_time = [[[NSDate alloc] init] timeIntervalSince1970];
Return Str.length < combo.length? STR: [str substringfromindex:str.length-combocode.length];
}] subscribenext:^ (ID x) {

Use this code to trigger the skill immediately after the condition is satisfied and the button is pressed.

Aggregatewithstart:reduce: The first parameter is the initial value, the second argument is a block, and the return value of the block is the next running parameter to the block. The operations I do in this block loop are:

1. For the delta calculation of time, if the distance from the last time the node is greater than 3 seconds, refresh time node to be timed again. When STR is less than 5, it returns, greater than 5, and five digits back.

2. If less than 3 seconds, each key information is aggregated into a string and the code is judged to contain the skill trigger.

3. The satisfying words trigger skill, the skill method's interior also refreshes the time node, and intercepts the running (retains the last 4 bits, prevents the previous loop end and the next loop to begin to satisfy the condition). The string continues to return if it is not satisfied.

Although the code is not very good-looking, but the function is implemented, feel a bit awkward, because functional programming advocates the reference is transparent without side effects, so the above need to record values and member variables is obviously not suitable for RAC, there should be a better way to achieve.

4. Other RAC operations

1 mapping: Flattenmap,map is used to map the content of the source signal to the new content

2) Combination: Concat: According to a certain sequence splicing signal, when multiple signals are issued, there is a sequential reception signal

3) ' Then ': Used to connect two signals, when the first signal is complete, will connect the signal returned by then

4 "Merge": The combination of multiple signals into a signal, any one signal has a new value when it will call

5) ' Combinelatest ': The combination of multiple signals, and get the latest values of each signal, must be each merged signal at least once sendnext, will trigger the merged signal.

6 ' Reduce ' aggregation: the content used for the signal emitted is a tuple, which aggregates the value of the signal emitting tuple into a value

7 Filter: Filters The signal, uses it to obtain the signal which satisfies the condition.

8) Ignore: a signal that ignores certain values.

9) Distinctuntilchanged: When the last value and the current value of a significant change will be signaled, otherwise it will be ignored

Take: The signal from the beginning to take n times altogether

Takelast: Take the last n signal, the prerequisite, the Subscriber must call to complete, because only the completion, you know how much signal total

Takeuntil: (racsignal *): Get the signal until a signal executes

Skip: (Nsuinteger): Skipping a few signals and not accepting

Switchtolatest: Used for signalofsignals (signal), sometimes the signal will also send signals, will be in the signalofsignals, get signalofsignals sent the latest signal

Donext: Before executing Next, the block is executed first

Docompleted: Before executing sendcompleted, this block is executed first

Deliveron: Content delivery switched to thread, side effects in the original thread, the code in the block when the signal was created called side effects

Subscribeon: Content delivery and side effects will be switched to the development thread

Interval timing: Signals are issued at intervals

Delay delay sending next.

21) In lieu of the agent:

Rac_signalforselector: Used as an alternative agent.

22) instead of KVO:

Rac_valuesandchangesforkeypath: Used to listen for property changes on an object.

23) Monitoring events:

rac_signalforcontrolevents: Used to listen for an event.

24) In lieu of notice:

rac_addobserverforname: Used to listen for a notification.

25 Listening text box text changes:

rac_textsignal: This signal is emitted whenever a text box is changed.

26 processing when the interface has multiple requests, need to get the data, to show the interface

Rac_liftselector:withsignalsfromarray:signals: When the incoming signals (array of signals), each signal at least sendnext once, the method that triggers the first selector parameter is triggered.

• Use note: Several signals, parameter one method on several parameters, each parameter corresponding to the signal emitted by the data

RAC has been labeled as a learning cost, poor readability, debug nightmares and other bad reviews, but with the evolution of recent years has been gradually accepted by enterprise-level projects, and become a mainstream function of response programming framework. RAC employing more and more, essays and blogs are more and more, the threshold of learning has been greatly reduced. And I think beginners do not have to start with all the operations and concepts are understood, you can start from the simple use of the first step of contact with higher-order syntax, which is easier to accept.

The above is a small set to introduce the REACTIVECOCOA code practice-more thinking, hope to help everyone!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.