【问题标题】:RxJava2, Android, Webview Create Observable in KotlinRxJava2、Android、Webview 在 Kotlin 中创建 Observable
【发布时间】:2019-01-27 12:15:10
【问题描述】:

刚刚开始尝试“Rx-ify”一些 Android 的 Webview 事件。

class PageStartData(val url: String, val favicon: Bitmap?)

myWebview.webViewClient = object: WebViewClient() {

   val pageStartEvents: Observable<PageStartData> = Observable.create{ emitter->
      override fun onPageStarted(view: WebView, url: String, favicon: Bitmap){
          emitter.onNext(PageStartData(url, favicon))
      }
   }

}

我发现 onPageStarted 函数超出了发射器 lambda 函数的范围。很简单,我敢肯定。如何解决?

感谢所有帮助。

【问题讨论】:

    标签: android kotlin rx-java2


    【解决方案1】:

    检查一下:

    sealed class WebViewEvent {
        data class PageStartData(val url: String?,
                                 val favicon: Bitmap?) : WebViewEvent()
    }
    

    ...

    class RxWebViewWrapper(private val webView: WebView) : ObservableOnSubscribe<WebViewEvent> {
        override fun subscribe(emitter: ObservableEmitter<WebViewEvent>) {
            webView.webViewClient = object :WebViewClient(){
                override fun onPageStarted(view: WebView?,
                                           url: String?,
                                           favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    emitter.onNext(WebViewEvent.PageStartData(url, favicon))
                }
            }
        }
    }
    

    ...

    val source = Observable.create<WebViewEvent>(RxWebViewWrapper(myWebview))
    

    【讨论】:

    • OK - 这使得 WebClient 范围在 O​​bservable 内部而不是相反。您将如何过滤事件以便只获取您关心的事件?
    • 您可以通过使用 rx filter operator source.filter { it is WebViewEvent.PageStartData }... 或使用 kotlin 的 when-is 构造 source.subscribe { when (it) { is WebViewEvent.PageStartData -&gt; { ... }} 来做到这一点
    • 非常感谢。这将极大地帮助我入门。我可以看到的另一个棘手问题是使用 ShouldInterceptRequest 执行此操作,它需要返回值。不要以为你也这样做了?
    【解决方案2】:

    可以通过PublishSubject完成

    myWebview.webViewClient = object : WebViewClient() {
            private val pageStartSubject = PublishSubject.create<PageStartData>()
            val pageStartEvents: Observable<PageStartData> = pageStartSubject
    
            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
                pageStartSubject.onNext(PageStartData(url, favicon))
            }
        }
    

    【讨论】:

    • 感谢您的回复。我试图暂时避免使用主题。不过,你是对的,这会奏效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    相关资源
    最近更新 更多