Detect Webview loading state using RxSwift

Easy way to get state of webiew loading using RxSwift.

Following extension is Observable of webview loading state. The boolean value is emitted when changing loading state.

extension Reactive where Base: WKWebView {

    var loading: Observable<Bool> {
        return observeWeakly(Bool.self, "loading", options: [.initial, .old, .new]) .map { $0 ?? false }
    }

}

The logic of detect start loading and finish loading is compare current loading state and previous one. Previous value is false and current value is true means start loading. Conversely, previous value is true and current value is false means finish loading. Previous value is emitted by loading.skip(1) that skip the first result and emit subsequence. We can get loading state by combining these value using Observable.zip and subscribe result.

func bind() {
  let loading = webView.rx.loading.shareReplay(1)

  Observable
    .zip(loading, loading.skip(1)) { !$0 && $1 }
    .filter { $0 }
    .subscribe { [weak self] _ in
      // Something you want to do when start loading.
    }.addDisposableTo(disposebag)

  Observable
    .zip(loading, loading.skip(1)) { $0 && !$1 }
    .filter { $0 }
    .subscribe { [weak self] _ in
      // Something you want to do when finish loading.
    }.addDisposableTo(disposebag)

}
  • このエントリーをはてなブックマークに追加