首页 \ 问答 \ 使用moya_modelMapper映射moya结果(Mapping moya result with moya_modelMapper)

使用moya_modelMapper映射moya结果(Mapping moya result with moya_modelMapper)

我的webservice类中有以下功能:

 func loadTransport() -> Observable<[TransportResponse]> {
        let nonce = "\(Date().timeIntervalSince1970)"
        let csaKey = try! config.apikey()
        let csaSecret = try! config.apiSecret()

        let csaSignature = crypto.generateSignature(nonce: nonce, url: "http://*****/v1/nmbs", body: "", secret: csaSecret)
        print("SIGNATURE = \(csaSignature)")

        let endpointClosure = { (target: TransportService) -> Endpoint<TransportService> in
            let url = target.baseURL.appendingPathComponent(target.path).absoluteString
            let endpoint = Endpoint<TransportService>(URL: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
            return endpoint.adding(newHttpHeaderFields: ["CSA-KEY": csaKey,"CSA-NONCE": nonce,"CSA-SIGNATURE": csaSignature])
        }



        let provider = RxMoyaProvider<TransportService>(endpointClosure: endpointClosure, plugins: [NetworkLoggerPlugin(verbose: true)])
        return provider
            .request(TransportService.nmbs)
            .filterSuccessfulStatusCodes()
            .mapArray(type: TransportResponse.self)
    }

在我的TransportViewModel中,我有这个init方法:

 init(webService: Webservice) {
        self.webService = webService

        title.value = String.localizedString(key: "transport_title")



        transportResponse = active.asObservable()
            .filter { $0 }
            .flatMap {  _  in
                return webService.loadTransport()
            }
            .map { response in
                return [TransportData(items: response)]
        }    
    }

问题是它出现在我的flatMap方法中,但它永远不会出现在flatMap下面的map中。

当我向我的webservice函数添加订阅部分时,如下所示:

 let provider = RxMoyaProvider<TransportService>(endpointClosure: endpointClosure, plugins: [NetworkLoggerPlugin(verbose: true)])
    provider
        .request(TransportService.nmbs)
        .filterSuccessfulStatusCodes()
        .mapArray(type: TransportResponse.self)
        .subscribe { event in
            switch event {
            case .next(let response):
                print(response)
            case .error(let error):
                print(error)
            default: break
            }
    }.addDisposableTo(disposeBag)

我看到我的回答是正确打印的。 任何人都可以帮我吗?


I have the following function in my webservice class:

 func loadTransport() -> Observable<[TransportResponse]> {
        let nonce = "\(Date().timeIntervalSince1970)"
        let csaKey = try! config.apikey()
        let csaSecret = try! config.apiSecret()

        let csaSignature = crypto.generateSignature(nonce: nonce, url: "http://*****/v1/nmbs", body: "", secret: csaSecret)
        print("SIGNATURE = \(csaSignature)")

        let endpointClosure = { (target: TransportService) -> Endpoint<TransportService> in
            let url = target.baseURL.appendingPathComponent(target.path).absoluteString
            let endpoint = Endpoint<TransportService>(URL: url, sampleResponseClosure: {.networkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
            return endpoint.adding(newHttpHeaderFields: ["CSA-KEY": csaKey,"CSA-NONCE": nonce,"CSA-SIGNATURE": csaSignature])
        }



        let provider = RxMoyaProvider<TransportService>(endpointClosure: endpointClosure, plugins: [NetworkLoggerPlugin(verbose: true)])
        return provider
            .request(TransportService.nmbs)
            .filterSuccessfulStatusCodes()
            .mapArray(type: TransportResponse.self)
    }

And in my TransportViewModel I have this init method:

 init(webService: Webservice) {
        self.webService = webService

        title.value = String.localizedString(key: "transport_title")



        transportResponse = active.asObservable()
            .filter { $0 }
            .flatMap {  _  in
                return webService.loadTransport()
            }
            .map { response in
                return [TransportData(items: response)]
        }    
    }

The problem is it comes in my flatMap method but it never comes inside the map below the flatMap.

When I add a subscribe part to my webservice function like this:

 let provider = RxMoyaProvider<TransportService>(endpointClosure: endpointClosure, plugins: [NetworkLoggerPlugin(verbose: true)])
    provider
        .request(TransportService.nmbs)
        .filterSuccessfulStatusCodes()
        .mapArray(type: TransportResponse.self)
        .subscribe { event in
            switch event {
            case .next(let response):
                print(response)
            case .error(let error):
                print(error)
            default: break
            }
    }.addDisposableTo(disposeBag)

I see that my response is correctly printed. Can anybody help me with this?


原文:https://stackoverflow.com/questions/41975515
更新时间:2023-09-09 09:09

最满意答案

这是一个有趣的问题,需要最长的公共子序列算法。 Tcl有一个已经在Tcllib中的那个,但它是用于列表的。 幸运的是,我们可以将字符串转换为带有split的字符列表:

package require struct::list

set a "the quick brown fox"
set b "the slow green fox"

set listA [split $a ""]; set lenA [llength $listA]
set listB [split $b ""]; set lenB [llength $listB]

set correspondences [struct::list longestCommonSubsequence $listA $listB]
set differences [struct::list lcsInvertMerge $correspondences $lenA $lenB]

现在,我们可以通过从addedchangeddeleteddifferences中选择部分来获取不匹配的部分:

set common {}
set unmatchedA {}
set unmatchedB {}
foreach diff $differences {
    lassign $diff type rangeA rangeB
    switch $type {
        unchanged {
            lappend common [join [lrange $listA {*}$rangeA] ""]
        }
        added {
            lappend unmatchedB [join [lrange $listB {*}$rangeB] ""]
        }
        changed {
            lappend unmatchedA [join [lrange $listA {*}$rangeA] ""]
            lappend unmatchedB [join [lrange $listB {*}$rangeB] ""]
        }
        deleted {
            lappend unmatchedA [join [lrange $listA {*}$rangeA] ""]
        }
    }
}

puts common->$common
# common->{the } ow {n fox}
puts A->$unmatchedA
# A->{quick br}
puts B->$unmatchedB
# B->sl { gree}

在这种情况下,我们看到以下对应关系( .是我插入的间隔符以帮助排列):

the quick br..ow.....n fox
the ........slow green fox

这是否正是你想要的,我不知道(并且在计算的差异中有更多的细节;它们只是有点难以阅读)。 如果更符合您的口味,您可以轻松切换到逐字对应。 它几乎只是删除splitjoin ......


This is an interesting problem that requires a longest common subsequence algorithm. Tcl's got one of those already in Tcllib, but it's for lists. Fortunately, we can convert a string into a list of characters with split:

package require struct::list

set a "the quick brown fox"
set b "the slow green fox"

set listA [split $a ""]; set lenA [llength $listA]
set listB [split $b ""]; set lenB [llength $listB]

set correspondences [struct::list longestCommonSubsequence $listA $listB]
set differences [struct::list lcsInvertMerge $correspondences $lenA $lenB]

Now we can get the parts that didn't match up by picking the parts from the differences that are added, changed or deleted:

set common {}
set unmatchedA {}
set unmatchedB {}
foreach diff $differences {
    lassign $diff type rangeA rangeB
    switch $type {
        unchanged {
            lappend common [join [lrange $listA {*}$rangeA] ""]
        }
        added {
            lappend unmatchedB [join [lrange $listB {*}$rangeB] ""]
        }
        changed {
            lappend unmatchedA [join [lrange $listA {*}$rangeA] ""]
            lappend unmatchedB [join [lrange $listB {*}$rangeB] ""]
        }
        deleted {
            lappend unmatchedA [join [lrange $listA {*}$rangeA] ""]
        }
    }
}

puts common->$common
# common->{the } ow {n fox}
puts A->$unmatchedA
# A->{quick br}
puts B->$unmatchedB
# B->sl { gree}

In this case, we see the following correspondences (. is a spacer I've inserted to help line things up):

the quick br..ow.....n fox
the ........slow green fox

Whether this is exactly what you want, I don't know (and there's more detail in the computed differences; they're just a bit hard to read). You can easily switch to doing a word-by-word correspondence instead if that's more to your taste. It's pretty much just removing the split and join

相关问答

更多
  • 请注意,regexp针对特定情况进行了简化,可能会进行改进以处理更复杂的情况(cdata,注释,引号等) 搜索 [^>]*>.*?<\/span>)(*SKIP)(?!)|([^<]*) 用。。。来代替 \1 regex101链接 怎么运行的 1:匹配我们不想要[^>]*>.*?<\/span>) 2:使用回溯动词避免回溯并且失败匹配(*SKIP)(?!) 3:在交替的下一步选择一个不匹配第一部分的模式 Note t ...
  • 这是一个有趣的问题,需要最长的公共子序列算法。 Tcl有一个已经在Tcllib中的那个,但它是用于列表的。 幸运的是,我们可以将字符串转换为带有split的字符列表: package require struct::list set a "the quick brown fox" set b "the slow green fox" set listA [split $a ""]; set lenA [llength $listA] set listB [split $b ""]; set lenB [ ...
  • 尝试这个 - 字符串trim 字符串 ? chars ? 返回一个等于字符串的值,除了由字符给出的集合中的任何前导字符或结尾字符被删除。 如果没有指定字符,则删除空格(空格,制表符,换行符和回车符)。 原始资料来源: - http://wiki.tcl.tk/10174 Try this - string trim string ?chars? Returns a value equal to string except that any leading or trailing characters fro ...
  • 如果您使用的是Tcl8.5或更高版本,则可以将扩展运算符{*}作为参数 catch {exec icv -vue {*}$setting -c $cell_name -i $gds_file $::RULE_SET } err 如果您使用的是Tcl8.4或更低版本,则可以使用eval命令 catch {eval exec icv -vue $setting -c $cell_name -i $gds_file $::RULE_SET } err If you are using Tcl8.5 or ab ...
  • 看看Tcl_SubstObj 。 这是[subst]命令的C等价物,这似乎是您要查找的内容。 正如你在评论中指出的那样,subst并没有完全做你想做的事情。 如果有帮助,下面的Tcl代码可能是你正在寻找的东西: > set mydata {mylist item $listitem group item {$group item}} > set listitem {1 2 3} > subst $mydata ;# error: can't read "group": no such variab ...
  • 只需使用-all标志即可。 我也会稍微更改你的脚本,通过使用-inline标志来直接获得结果而不是依赖于match变量,因为当你得到多个匹配时,它只会保留最后一个匹配。 我还修复了代码段中的一些错误。 set data1 {asdGETdf ferGETfhgDOT} ;#data1 is the given string foreach index $data1 { set result [regexp -all -inline -- {HAT|GET|DOT} $index] puts "\n$ ...
  • 您需要在line变量上使用美元符号来获取其值: if [ string match $::StringToFind $line ] { 此外,引用if命令的条件是一个好习惯: if {[string match $::StringToFind $line]} { You need to use the dollar sign on the line variable to get its value: if [ string match $::StringToFind $l ...
  • 尝试这个: NestedBraces : '{' (~('{' | '}' | '\\') | '\\' ('{' | '}') | NestedBraces)* '}' ; 在内部循环中,您匹配: ~('{' | '}' | '\\') // anything other than a '{', '}' and '\' | // OR '\\' ('{' | '}') // an escaped '{' or '}' | ...
  • 单个内存对象(例如,字符串)的当前最大大小为2GB。 这是 64位平台上的已知错误 (长期存在),但修复它需要显着的ABI和API中断更改,因此它不会出现在Tcl 9.0之前。 字符串和列表之间的区别在于字符串存储在单个内存块中,而列表存储在指向元素的指针数组中。 您可以在列表中获得256k元素没问题,但之后您可能会遇到问题,因为数组达到2GB限制。 Tcl的值对象可以同时是列表和字符串; 关于Tcl的“一切都是字符串”的格言并不是真的,只是所有东西都可以序列化为一个字符串。 返回列表不会强制它转换为字符串 ...
  • 要从路径获取最后一个组件,您将使用file tail : file tail $string 如果你碰巧想要使用puts : puts [file tail $string] To get the last component from a path, you would use file tail: file tail $string And if you happen to want it using puts: puts [file tail $string]

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。