簡體   English   中英

iOS - 合並 - 將發布者類型更改為子類型

[英]iOS - Combine - Change Publisher type to child type

我有這兩個 Codable 對象:

struct Parent: Codable {
    let name: String
    let children: [Child]
}

struct Child: Codable {
    let name: String
} 

我創建的匹配這個 json :

{
    name: "test"
    children: (
        {
          name: "test2"
        },
        {
          name: "test3"
        }
     )
}

我使用以下方法檢索 json 並將其解碼為 Parent 對象:

func parent(_ url: String) -> AnyPublisher<Parent, Error> { 
    return dataFromURL(url)
        .map(\.value)
        .eraseToAnyPublisher()
}

struct Result<T> {
    let value: T
    let response: URLResponse
}

func dataFromURL<T: Decodable>(_ url: String, _ decoder: JSONDecoder = JSONDecoder()) -> AnyPublisher<Result<T>, Error> {
    let request = URLRequest(url: URL(string:url)!)
    return URLSession.shared
        .dataTaskPublisher(for: request)
        .tryMap { result -> Result<T> in
            let value = try decoder.decode(T.self, from: result.data)
            return Result(value: value, response: result.response)
        }
        .receive(on: DispatchQueue.main)
        .eraseToAnyPublisher()
}

它有效,但我想要一種方法來檢索子數組而不是父對象,如下所示:

func children(_ url: String) -> AnyPublisher<[Child], Error>  

但我不知道我需要改變什么.. 任何幫助將不勝感激,謝謝!

你只需要調用你的parent函數並在它的Publisher上調用map來取回它的children屬性。

func children(from url: String) -> AnyPublisher<[Child], Error> {
    return parent(url)
        .map(\.children)
        .eraseToAnyPublisher()
}

與您的問題無關,但我建議擺脫您的Result類型。 首先,它與 Swift 的內置Result類型沖突。 其次,在網絡請求成功的情況下存儲URLResponse ,返回有效數據並沒有真正增加任何價值。 URLResponse主要在失敗的情況下保存值,或者如果請求沒有返回值,而是成功響應代碼( URLResponse等)。

更新:如果你想擺脫你的parent(_:)方法,你只需要將map(\\.children)調用鏈接到原始parent(_:)方法的內容。 為了讓編譯器推斷dataFromURL(_:)方法的通用返回類型,您只需在第二次map調用中將KeyPath指定為\\Parent.children

func children(from url: String) -> AnyPublisher<[Child], Error> {
    return dataFromURL(url)
        .map(\.value)
        .map(\Parent.children)
        .eraseToAnyPublisher()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM