Reactivecocoa/rxswift Note One

Source: Internet
Author: User

Original: Reproduced please indicate the source

Reactivecocoa/rxswift

The Native app has a large part of the time waiting for events to occur and then responds to events such as

1. Wait for the network request to complete,

2. Wait for the user's Operation ,

3. Wait for certain status values to change , etc.

Wait until these events have occurred, and then do further processing.

But these waits and responses do not have a unified approach. Delegate, Notification, Block, KVO, often do not know which is the most suitable. Sometimes you need to chain or compose a few events, you need more than one state variable, and more state variables, the complexity comes up. To solve these problems,GitHub engineers developed the Reactivecocoa.

Concept

Socket :Signal, socket is responsible for obtaining and providing electrical <-> Observable

Plug :subscriber- plug for use of electrical <-> Observer

Use

Signal Gets the data, it calls Subscriber 's Sendnext, Sendcomplete, Senderror method to send the data to subscriber,

<>

RxSwift : OnNext oncomplete onError

Subscriber Naturally also has the means to obtain data transmitted, such as:[signal subscribeNext:error:completed]. So as long as there is no sendcomplete and senderror, the new value will be transmitted through the Sendnext stream.

<>

RxSwift:

Reloaddataitem.rx_tap

. Subscribenext {[unowned self] in

Self.initialization ()

}.adddisposableto (Disposebag)

RAC is based on the kvo

Principle :

Racobserve uses KVO to monitor the property changes, so long as username is changed by itself or externally, the block is executed. But not all the property can be Racobserve, the property must support Kvo, such as Nsurlcache currentdiskusage You can't be racobserve.

Flexibility:

Signal is very flexible, it can be modified (map), filtered (filter ), superimposed (combine), concatenated (chain), which helps to deal with more complex situations,

RAC (Self.loginbutton, enabled) = [racsignal

Combinelatest: @[

Self.usernameTextField.rac_textSignal,

Self.passwordTextField.rac_textSignal,

Racobserve (Loginmanager.sharedmanager, Loggingin),

Racobserve (self, loggedIn)

] reduce:^ (nsstring *username, NSString *password, NSNumber *loggingin, NSNumber *loggedin) {

return @ (username.length > 0 && password.length > 0 &&!loggingin.boolvalue &&!lo         Ggedin.boolvalue); }];

1. This value will be returned (Sendnext) as long as the value of the Usernametextfield is changed.

2. Combinelatest need to have at least one sendnext per signal.

3.the role of reduce is to return a new value based on the value received, which is @ (yes) and @ (NO), which must be an object.

<>

RxSwift:

Observable. combinelatest (Calendarrequest, Schedulerequest, calendarvc.rx_didscrolltomonth) {

(schedulelist: $, Schedule: $, didscroll:$2)

}

. Onalerterror ()

. Subscribe (

OnNext: {[unowned self] x in

Self.updatedata (X.schedulelist, Schedule:x.schedule, Noticelist:nil)

},

OnError: {[unowned self] Error in

//

},

OnCompleted: {

//

}

). Adddisposableto (Self.disposebag)

Side Effect

Or the above code, if there are multiple subscriber, then signal will be triggered again, the console will output two times triggered. This may be what you want, maybe not. If you want to avoid this situation, you can use the replay method, its role is to ensure that signal is only triggered once, and then Save the value of Sendnext , the next time there is a new subscriber, Send the cached data directly.

Cocoa Categories

UIView Categories

1. [[Alertview rac_buttonclickedsignal] subscribenext:^ (NSNumber *indexnumber) {

Todo

}];

RAC provides a method for UITableViewCell:rac_prepareforreusesignal, which is the function of telling the cell when the cell is about to be reused. Imagine that there are multiple buttons on the cell, and the cell addTarget:action:forControlEvents each button when it is initialized, and it needs to remove the target first when it is reused. , the following code makes it easy to solve this problem:

    1. [[[Self.cancelbutton
    2. Rac_signalforcontrolevents:uicontroleventtouchupinside]
    3. TakeUntil:self.rac_prepareForReuseSignal]
    4. subscribenext:^ (UIButton *x) {
    5. Do other things
    6. }];

Rac_command is a command that executes when the button is pressed, and the command is executed to return a signal, with signal flexibility. For example, click on the Voting button, first to determine if there is no login, if there is an HTTP request, there is no popup landing box, you can do so.

Notificationcenter Category

Nsnotificationcenter, By default Nsnotificationcenter uses Target-action way to handle notification, which requires a different method to be defined. This involves one of two major challenges in the field of programming: Name. with RAC, there is Signal, with Signal can subscribe, so Notificationcenter can deal with this, There's no need to worry about removing observer .

    1. [[[Nsnotificationcenter Defaultcenter] rac_addobserverforname:@ "Mynotification" Object:nil] subscribeNext:^ ( Nsnotification *notification) {
    2. NSLog (@ "Notification Received");
    3. }];

Nsobject+racdeallocating.h

As the name implies is in a A piece of code that executes when the dealloc of an object is triggered.

    1. Nsarray *array = @[@ "foo"];
    2. [[Array rac_willdeallocsignal] subscribecompleted:^{
    3. NSLog (@ "Oops, I'll Be Gone");
    4. }];
    5. Array = nil;

Nsobject+racselectorsignal.h

This category has rac_signalforselector: and rac_signalforselector:fromprotocol: These two methods. First look at the previous one, which means that when a selector is called, it executes a specified code, which is equivalent to a hook. For example, after clicking on a button, record a log. The latter indicates that the selector implements a protocol, so it can be used to implement Delegate.

MVVM

The biggest difference between MVVM and MVC is a ViewModel, which is directly tied to view and knows nothing about view . For example,ViewModel is a seasoning, it does not care about what is cooked. It can play the role of model, but in fact it is the model of the intermediary, so that when the model of the API changes, or by local storage into a remote API call,the ViewModel The public API can remain unchanged.

The advantage of using ViewModel is that it makes the controller simpler and lighter, and the ViewModel is relatively independent and more convenient to test and reuse. What should the controller do then? In the MVVM system, aController can be viewed as a View, so its main work is

Handling layouts ,

Animations ,

Receive system events ,

Presentation UI.

MVVM also has a very important concept is data binding, the rendering of view requires data, this data is provided by ViewModel, the view of the data After binding with ViewModel data, the other party will be able to receive information from both parties in the future as long as one party changes. Here is a viewmodel Base Class from GitHub Open source.

Other

RAC has a few caveats to use, so you can refer to the official Designguildlinesfor a brief talk.

When a signal is subscribe by a subscriber , When will this Subscriber be removed ? The answer is when subscriber is Sendcomplete or senderror, or it is called manually [disposable dispose].

When Subscriber is disposed, all the subscriber-related work is stopped or canceled, such as HTTP requests, and resources are freed.

Signal events is linear and does not appear in concurrency unless scheduler is specified by the display. So-subscribenext:error:completed: The block does not need to be locked or synchronized, other events will be queued until block processing is complete.

Errors has priority, if there are multiple signals are simultaneously listening, as long as one of the signal senderror, then the error will be transmitted to subscriber immediately, and cause signals to terminate execution. Equivalent to exception.

When generating signal , it is best to specify name,-setnamewithformat: easy to Debug.

Do not block in block code.

Reactivecocoa/rxswift Note One

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.