Moya and RxSwift use

Source: Internet
Author: User

For example, using afnetworking in OC, Swift we use Alamofire to do the network library. and Moya on the basis of Alamofire also encapsulated a layer:

1. About Moya

Moya

Officials say moya The following features are-_-:

    • Compile-time check for proper API endpoint access.
    • Enables you to define different endpoint enumeration values corresponding to the corresponding purpose of the more explicit.
    • Improve test status and make unit testing easier.
2. Start 1. Create an enumeration API

Just like this:

enum Apimanager { case getnewslatest// Get the latest news  case getstartimage// Start Interface Image Acquisition  case GetVersion (String)// software version query  case getthemes// topic daily List View   Case Getnewsdetail (INT)// get press Details }

2. Implementing the TargetType Agreement

Just like this:

extension Apimanager:targettype {///The target ' s base ' URL '.var baseurl:url {returnUrl.init (string:"http://news-at.zhihu.com/api/")!} ///The path to is appended to ' BaseURL ' to form the full ' URL '.var path:string {SwitchSelf { Case. Getnewslatest:return "4/news/latest"  Case. Getstartimage://Start-image After the image resolution, accept any Number*number format, number is any non-negative integer, the return value is the same. return "4/start-image/1080*1776"  Case. GetVersion (Let version)://The number in the last part of the URL represents the version of "informed daily" installed .return "4/version/ios/"+version Case. Getthemes:return "4/themes"  Case. Getnewsdetail (LetID):return "4/news/\ (ID)" }  } ///The HTTP method used in the request.var Method:Moya.Method {return.Get} ///The parameters to is incoded in the request.var parameters: [String:any]? { returnNil}///The method used for parameter encoding.var parameterencoding:parameterencoding {returnUrlencoding.default} ///provides stub data for use in testing.var sampledata:data {return "". Data (using: String.Encoding.utf8)!} ///The type of HTTP task to is performed.var task:task {return. Request}///Whether or not to perform alamofire validation. Defaults to ' false '.var validate:bool {return false} }

Here, you can set the parameters of the request, such as Url......method......para.

3. Use

Moyais very simple to use, TargetType after each protocol is defined target , you can use the Moya start to send the network request directly. Just like this:

Let Provider = moyaprovider<apimanager>in// does something with result}

3. With Rxswift

Moyaitself is already a very convenient to use, can write very concise and elegant code of the network Packaging library, but let Moya it become more powerful because Functional Reactive Programming of its extension, specifically for RxSwift and ReactiveCocoa extension, through the combination of these two libraries, can let Moyabecome more powerful. I chose RxSwift for two reasons, one is RxSwift relatively lightweight library, syntax updates relatively small, I have used before ReactiveCocoa , some large version of the update requirements rewrite a lot of code, the second more important reason is because RxSwift there is a full ReactiveX support behind , including,,,,,, Inside, Java JS .Net Swift Scala They all use ReactiveX logic, which means that once you've learned one of them, you can quickly get started ReactiveX in other languages.

MoyaProvides a very RxSwift extensive extension:

Let Provider = rxmoyaprovider<apimanager>in//doessomething with posts  Print (JSON)}). Adddisposableto (Disposebag)

Explain:

    • RxMoyaProviderIs MoyaProvider the subclass that is right for RxSwift the extension

    • filterSuccessfulStatusCodes()is Moya to RxSwift provide an extension method that, as the name implies, can be successfully requested by the network, ignoring the other

    • mapJSON()is also Moya RxSwift an extension method that can parse the returned data into a JSON format

    • subscribeis a RxSwift method, for a layer of processing of a Observable subscription onNext observer , once the data is obtained JSON , it will be processed by the corresponding line

    • addDisposableTo(disposeBag)is RxSwift an automatic memory processing mechanism that, ARC like a bit, automatically cleans up unwanted objects.

4. With Handyjson

In practice, network requests are often tightly connected to the data layer ( Model ), specifically, in our example, we typically need to create a class to unify the management of the data and then map the resulting JSON data to the data layer ( Model ).

struct Menumodel:handyjson {var others: [Thememodel]?  struct  Thememodel:handyjson {var color:string?  var thumbnail:string?  ID: Int? var description:string? var name:string? }

Then create the ViewModel class to create the specific request method:

Classprivate Let Provider = rxmoyaprovider<apimanager>=    in}, Oncompleted:nil, Ondisposed:nil). Adddisposableto (Dispose)}}  

Here's an explanation:
I am here to pass the requested data through the closure of the packet, of course, can not do so. Personal preferences Questions:

This is for   RxSwift     observabletype and   Response Write a simple extension method   Mapmodel , using the Model   class that we wrote, to map JSON data to   in one step; Model .

where E = = Response { public func mapmodel<t:handyjson> (_ Type:t.type), observable<t> {  returninreturn  observable.just (Response.mapmodel (t.self))}}} Extension Response {func Mapmodel<T:HandyJSON> (_ Type:t.type)= string.init (data:data, encoding:. UTF8)return jsondeserializer<t>.deserializefrom (json:jsonstring)! }}

Articles reproduced from Three_zhang's Blog to make records

Moya and RxSwift use

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.