RxSwift reload tableview

前端 未结 3 1650
野的像风
野的像风 2020-12-21 07:04
let officialAccountObservable : Observable<[SearchUser]> = SearchAPI.sharedAPI.suggestAccounts()

        officialAccountObservable.bind(to: tableView.rx.items         


        
相关标签:
3条回答
  • 2020-12-21 07:45

    I recommend you to create a Refreshable decorator.

    class Refreshable<T>: ObservableType {
    
        typealias E = T
        func subscribe<O:ObserverType>(_ observer: O) -> Disposable where O.E == E {
            return refreshMeans
                .flatMapLatest{ [unowned self] in
                    return self.origin.asObservable()
                }
                .subscribe(observer)
        }
    
        private let disposeBag = DisposeBag()
        private let origin: Observable<T>
        init(origin: Observable<T>, updatedOn: Observable<Void> = .never()) {
            self.origin = origin
            updatedOn.bind(to: refreshMeans).disposed(by: disposeBag)
        }
    
        private let refreshMeans = BehaviorSubject<Void>(value: ())
    
        func refresh() {
            refreshMeans.on(.next())
        }
    
    }
    

    wrap your officialAccountObservable into a Refreshable:

    let officialAccountObservable : Refreshable<[SearchUser]> = Refreshable(origin: SearchAPI.sharedAPI.suggestAccounts())
    

    and call refresh when you need to refresh it:

    if(result == true){
        officialAccountObservable.refresh()
    }
    
    0 讨论(0)
  • 2020-12-21 07:46

    AFAIK, this is the standard way of doing this -

    let source = PublishSubject<Observable<[SearchUser]>>()
    let officialAccountObservable: Observable<[SearchUser]> = source.switchLatest()
    source.onNext(suggestAccounts()) // every call will refresh your table
    
    0 讨论(0)
  • 2020-12-21 07:53

    I think the problem you are having right now is that when you create the observable which makes the Alamofire call, it only ever gets executed once since you have no way to make another call.

    What you might want to do is something like Maxim Volgin suggested: use a subject.

    A subject is a input as well as a output at the same time. In your case, the output would be the data for your tableview and you would bind it as you already do.

    Then, use the pull to refresh or another suiting mechanism for reloading to make the web service call and publish the results to the subject (which then will update your tableview).

    Keep in mind that subjects also populate onError and onComplete calls up to the observer so make sure you deal with possible errors in your web service call before publishing the result to the subject.

    I found this site incredible helpful to get a better understanding of RxSwift: http://swiftpearls.com/

    You should check it out. Especially the RxSwift for Dummies is great to get the basic understanding of how things are supposed to work.

    0 讨论(0)
提交回复
热议问题