Combine对XTDemo中VM的改造

# 前言

上篇博文中,已经将 RxSwift 替换为了 Combine,开头也提到了仅仅简略的运用 Combine。此篇中作为这两天学习的一个小结。经过对 ViewModel 的改造来进一步学习 Combine 的运用。

  • 文中不会过多介绍 CombinePublisers, Subscribers 的类型——官方注释很详细并且上篇中也有相关博客/文章链接。

  • 文中以 XTDemo 的 TextureDemoViewController 的改造为例进行说明。

  • 效果图:

    Combine对XTDemo中VM的改造

阅览本文您将得到:

  • 运用 Publisher 封装 MJRefresh 改写事情(UIContol 与此相似)。

  • 运用 Subscriber 封装 MJRefresh 结束改写的办法

  • ViewModelInput 中办法调用改为订阅者(AnySubscriber<Input, Never> )特点

  • 经过操作符创立新的 Publisher

本文中将涉及的办法主要有:

  • Publisher

    func receive<S>(subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input
    
  • AnySubscriber

    @inlinable public init<S>(_ s: S) where Input == S.Input, Failure == S.Failure, S : Subscriber
    public init<S>(_ s: S) where Input == S.Output, Failure == S.Failure, S : Subject
    

# Publiser 和 Publishers, Subscriber 和 SubScribers

官方注释上咱们能很明白的知道:

  • Publishers发布者(Publisher) 的命名空间。
  • 所有 发布者(Publisher) 的操作符(func)的完结都是经过 Publishers 内部界说类型完结的。
/// A namespace for types that serve as publishers.
///
/// The various operators defined as extensions on ``Publisher`` implement 
/// their functionality as classes or structures 
/// that extend this enumeration. For example, 
/// the `contains(_:)` operator returns a `Publishers.Contains` instance.
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
public enum Publishers {
}

相同的 Subscribers 也是 用作订阅者的类型的称号空间AnyCancellable 是对 Cancellable 的类型摸除。

Subscribersextension 中官方供给了 Subscribers.SinkSubscribers.Assign 等。 Subscribers.SinkPublisherfunc sink(xx) 对应,Subscribers.Sink 恪守 Cancellable 协议。 Subscribers.Assign 与之相似。

# 运用 AnySubscriber 界说 ViewModel.Input

ViewModel 的界说和 RxSwift弥补 中所论述的相同,这儿需求将 Input 协议从 func xx 转变为订阅者 特点。运用 AnySubscriber 不限制内部详细运用类型,同时隐藏内部完结。

protocol TextureDemoViewModelInputs {
    var viewDidLoadSubscriber: AnySubscriber<Void, Never> { get }
    var refreshSubscriber: AnySubscriber<Void, Never> { get }
    var moreDataSubcriber: AnySubscriber<Void, Never> { get }
}

例如:viewDidLoadSubscriber 对应原来的 func viewDidload()。 在 ViewModel 对其完结有两种办法:

  • 直接运用 Subject 转化:

    fileprivate let moreDataSubject = PassthroughSubject<Void, Never>()
    var moreDataSubcriber: AnySubscriber<Void, Never> {
        self.moreDataSubject.asAnySubscriber()
    }
    
  • 运用运用 Subscribers.xxx 创立:

    var viewDidLoadSubscriber: AnySubscriber<Void, Never> {
        let sinkSubscriber = Subscribers.Sink<Void, Never>.init { _ in
            print("viewDidLoad Sink finished! ____&")
        } receiveValue: { [weak self] _ in
            self?.queryNewData()
        }
        return .init(sinkSubscriber)
    }
    

# 为 MJRefresh 添加 Combine 支持

经过对 Input 的改造,咱们很简单经过 Subscribers.Sink 完结 MJRefreshHeaderMJRefreshFooter 结束改写的 subscriber

extension MJRefreshHeader {
    // @NOTE: - 可所以 办法, 也可所以 核算特点, 都不支持屡次加入到 发布者 中
    func subscriber() -> AnySubscriber<Void, Never> {
        let sinkSubscriber = Subscribers.Sink<Void, Never>.init { _ in
            // To be continue
        } receiveValue: { [weak self] _ in
            self?.endRefreshing()
        }
        return .init(sinkSubscriber)
    }
}
extension MJRefreshFooter {
    func subscriber() -> AnySubscriber<Bool, Never> {
        let sinkSubscriber = Subscribers.Sink<Bool, Never>.init { _ in
            // To be continue
        } receiveValue: { [weak self] hasMore in
            (hasMore ? { self?.endRefreshing() } : { self?.endRefreshingWithNoMoreData() })()
        }
        return .init(sinkSubscriber)
    }
}

对上/下拉改写供给 Publisher 封装,需求用到自界说 PublisherSubscription 来组合完结。

本文想要将发送信息的 MJRefreshComponent 回来(也回来 Void),Subscription 界说如下:

fileprivate final class MJRefreshingSubscription<S: Subscriber, Control: MJRefreshComponent>: Subscription where S.Input == Control {
    private var subscriber: S
    private let control: Control
    init(subscriber: S, control: Control) {
        self.subscriber = subscriber
        self.control = control
        //control.setRefreshingTarget(self, refreshingAction: #selector(refreshing))
        // FIXDE: - 注意循环引证: control -> refreshingBlock -> control
        control.refreshingBlock = { [weak control] in
            if let ctr = control {
                _ = subscriber.receive(ctr)
            }
        }
    }
    // To be continue
    func request(_ demand: Subscribers.Demand) {
        guard demand > 0 else { return subscriber.receive(completion: .finished) }
        // 不作任何处理, 已经在 refreshingBlock 中告诉 subscriber 接纳 control
    }
    func cancel() {
        // To be continue
        subscriber.receive(completion: .finished)
    }
}

Publisher 界说如下:

fileprivate final class MJRefreshingPublisher<Control: MJRefreshComponent>: Publisher {
    typealias Output = Control
    typealias Failure = Never
    let control: Control
    init(control: Control) {
        self.control = control
    }
    // To be continue
    func receive<S>(subscriber: S) where S : Subscriber, Never == S.Failure, Control == S.Input {
        let subscription = MJRefreshingSubscription(subscriber: subscriber, control: control)
        subscriber.receive(subscription: subscription)
    }
}

MJRefreshComponent 的改写供给 Publisher 支持:

extension MJRefreshComponent {
    var publisherRefreshing: AnyPublisher<MJRefreshComponent, Never> {
        return MJRefreshingPublisher(control: self).eraseToAnyPublisher()
    }
}

# 经过操作符创立新的 Publisher

Outputs 协议界说如下:

protocol TextureDemoViewModelOutputs {
    var newDataPublisher: AnyPublisher<[DynamicDisplayType], Never> { get }
    var endRefreshPublisher: AnyPublisher<Void, Never> { get }
    var moreDataPublisher: AnyPublisher<[DynamicDisplayType], Never> { get }
    var endMoreRefreshPublisher: AnyPublisher<Bool, Never> { get }
    var toastPublisher: AnyPublisher<String, Never> { get }
}

ViewModel 中咱们任然需求经过 PassthroughSubject(或许 CurrentValueSubject) 来操控数据请求的机遇(send(value), 或许 asAnySubscriber())。运用的 Subject 界说如下:

fileprivate let refreshSubject = PassthroughSubject<Void, Never>()
fileprivate let topicSubject = PassthroughSubject<Void, Never>()
fileprivate let moreDataSubject = PassthroughSubject<Void, Never>()

OutputsPublisher 都是经过他们转化而来的。注意:需求运用 share() 操作符,来达到 Publisher 共享的作用(简略理解为引证类型和值类型的差异),下面是需求共享的 publisher

// FIXED: - 有必要运用存储特点, share() 才能保证屡次订阅不会产生屡次的请求
private lazy var newDataResultPublisher: AnyPublisher<Result<[DynamicDisplayType], BundleJsonDataError>, Never> = {
    self.createNewDataPublisher()
        .share()
        .eraseToAnyPublisher()
}()
private lazy var moreDataResultPublisher: AnyPublisher<[DynamicDisplayType]?, Never> = {
    self.createMoreDataPublisher()
        .share()
        .eraseToAnyPublisher()
}()

Outputs 中其他发布者转化入下:

var newDataPublisher: AnyPublisher<[DynamicDisplayType], Never> {
    return self.newDataResultPublisher
        .compactMap { result -> [DynamicDisplayType]? in
            if case .success(let list) = result {
                return list
            }
            return nil
        }
        .onMainScheduler()
}
var endRefreshPublisher: AnyPublisher<Void, Never> {
    self.newDataResultPublisher
        .map { _ in }
        .onMainScheduler()
}
var moreDataPublisher: AnyPublisher<[DynamicDisplayType], Never> {
        self.moreDataResultPublisher
            .compactMap { $0 }
            .onMainScheduler()
    }
var endMoreRefreshPublisher: AnyPublisher<Bool, Never> {
    self.moreDataResultPublisher
        .map { _ in kDynamicFileIndex < 5 }
        .merge(with: self.newDataResultPublisher.map { _ in true })
        .onMainScheduler()
}
var toastPublisher: AnyPublisher<String, Never> {
    self.newDataResultPublisher
        .compactMap { result -> String? in
            switch result {
            case .success(_):
                return nil
            case .failure(_):
                return ">_< 数据丢掉了!"
            }
        }
        .merge(with: self.moreDataResultPublisher.compactMap { $0 == nil ? ">_< 数据丢掉了!" : nil })
        .onMainScheduler()
}

# 在 VC 中运用

至此,ViewModelMJRefresh 封装完结。在 VC 中替换 MJRefreshblockpublisher

func eventListen() {
    mjHeader.publisherRefreshing
        .map { _ in }
        .receive(subscriber: viewModel.input.refreshSubscriber)
    mjFooter.publisherRefreshing
        .map { _ in }
        .receive(subscriber: viewModel.input.moreDataSubcriber)
}

绑定 viewModel

func bindViewModel() {
    // To be contniue 为什么没有运用 subscriber?
    viewModel.output.newDataPublisher
        .sink { [weak self] list in
            self?.reloadData(with: list)
        }
        .store(in: &cancellable)
    viewModel.output.endRefreshPublisher
        .receive(subscriber: mjHeader.subscriber())
    viewModel.output.moreDataPublisher
        .sink { [weak self] list in
            self?.insertData(with: list)
        }
        .store(in: &cancellable)
    viewModel.output.endMoreRefreshPublisher
        .receive(subscriber: mjFooter.subscriber())
    viewModel.output.toastPublisher
        .sink { [weak self] msg in
            self?.toast.showCenter(message: msg)
        }
        .store(in: &cancellable)
}

# 弥补

文中办法弥补:

  • queryNewData

    func queryNewData() {
        kDynamicFileIndex = 0
        self.refreshSubject.send()
        self.topicSubject.send()
    }
    
  • asAnySubscriber

    extension Subject {
        public func asAnySubscriber() -> AnySubscriber<Self.Output, Self.Failure> {
            .init(self)
        }
    }
    
  • onMainThread

    extension Publisher {
        public func onMainScheduler() -> AnyPublisher<Self.Output, Self.Failure> {
            receive(on: RunLoop.main).eraseToAnyPublisher()
        }
    }
    

UIButton 的拓宽

extension UIButton {
    public func subscriber(forTitle state: UIControl.State) -> AnySubscriber<String, Never> {
        let sinkSubscriber = Subscribers.Sink<String, Never> { _ in
        } receiveValue: { [weak self] value in
            self?.setTitle(value, for: state)
        }
        return .init(sinkSubscriber)
    }
}
extension UIControl {
    public func publisher(forAction event: UIControl.Event) -> AnyPublisher<UIControl, Never> {
        ControlPublisher.init(control: self, event: event).eraseToAnyPublisher()
    }
}

接下来:

鄙人一篇博文中咱们来研究下 combine 的内存管理,并弥补文中 // To be contniue 的部分。

感谢您的阅览,有问题可留言。