SwiftUI

Combine-AnyPublisher

2020-05-05  本文已影响0人  YungFan
import Combine

// p1类型: Publishers.FlatMap<Publishers.Sequence<[Int], Never>, Publishers.Sequence<[[Int]], Never>>
let p1 = [[1, 2, 3], [4, 5, 6]]
    .publisher
    .flatMap { $0.publisher }

// p2类型: Publishers.Map<Publishers.FlatMap<Publishers.Sequence<[Int], Never>, Publishers.Sequence<[[Int]], Never>>, Int>
let p2 = p1.map { $0 * 2 }

// p3类型: AnyPublisher<Int, Never>
let p3 = p2.eraseToAnyPublisher()
import UIKit
import Combine

class DataPublisher {    
    private var dataPublisher: AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure>
    
    var cancellable: AnyCancellable?
    
    init(){      
        let url = URL(string: "http://v.juhe.cn/toutiao/index?type=top")
        let request = URLRequest(url: url!)
        let session = URLSession.shared
        
        // 1. 创建发布者
        self.dataPublisher = session.dataTaskPublisher(for: request).eraseToAnyPublisher()
        
        // 2. 订阅
        cancellable = dataPublisher
            .receive(on: DispatchQueue.main).sink(receiveCompletion: {_ in
            }) { (data: Data, response: URLResponse) in               
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读