暂无描述

GroupViewModel.swift 3.4KB

    // // GroupViewModel.swift // PaiAi // // Created by zhengjianfei on 2017/1/4. // Copyright © 2017年 FFIB. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources public protocol GroupViewModelDelegate: class { func didSelect(_ items: [PhotoItem], currIndex: Int) func navigateToGroupDetail(_ item: GroupItem) } public class GroupViewModel { private let disposeBag = DisposeBag() private var repository: GroupPhotoRepository private var _isLoading = PublishSubject<Void>() private let items = BehaviorRelay<[PhotoItem]>(value: []) private let _hasData = BehaviorRelay<Bool>(value: false) public var groupItem: BehaviorRelay<GroupItem> public var groupName: Observable<String> { return groupItem.asObservable().flatMapLatest({ (item) -> Observable<String> in return Observable.just(item.group_name) }) } public var groupAvatar: Observable<String> { return groupItem.asObservable().flatMapLatest({ (item) -> Observable<String> in return Observable.just("Group\(item.group_default_avatar)") }) } public var isLoading: Observable<Void> { return _isLoading.asObservable() } public var hasData: Observable<Bool> { return _hasData.asObservable() } public var contents: Observable<[AnimatableSectionModel<Int, PhotoItem>]> { return items.map({ model in return [AnimatableSectionModel(model: 0, items: model)] }) } public weak var delegate: GroupViewModelDelegate? public init(groupItem: GroupItem) { self.repository = GroupPhotoRepository(groupId: groupItem.group_id) self.groupItem = BehaviorRelay<GroupItem>(value: groupItem) ShareRecentGroupInfo.add(groupItem) } public func reload() { repository.load() .subscribe(onSuccess: {[weak self] (result) in guard let `self` = self else { return } self._isLoading.onNext(()) self.items.accept(result) self._hasData.accept(result.count > 0) }, onError: {[weak self] (error) in guard let `self` = self else { return } self._isLoading.onNext(()) }).disposed(by: disposeBag) } public func submit(data: Data) { repository.upload(data: data).subscribe(onSuccess: { [weak self] result in guard let `self` = self else { return } self.items.accept(result) Toast.show(message: "照片已上传") self._isLoading.onNext(()) }) {[weak self] (error) in guard let `self` = self else { return } Toast.show(message: "照片失败") self._isLoading.onNext(()) }.disposed(by: disposeBag) } public func layoutSizeForIndexPath(_ indexPath: IndexPath) -> CGSize { let item = items.value[indexPath.row] let w = item.photo_thumbnail_w let h = item.photo_thumbnail_h // header 42, footer: 32 return CGSize(width: w, height: h + 74) } } /// GroupViewModelDelegate public extension GroupViewModel { func didSelect(_ index: Int) { delegate?.didSelect(items.value, currIndex: index) } @objc func navigateToGroupDetail() { delegate?.navigateToGroupDetail(groupItem.value) } }