刚开始尝试“ 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函数的范围。很简单,我确定。如何解决?
感谢所有帮助。
答案 0 :(得分:2)
检查:
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))
答案 1 :(得分:1)
可以通过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))
}
}