如何以最短的方式创建自定义事件?
有customWebViewClient
带有Override函数OnPageFined
。关于触发该函数的通知mainViewModel
的最短方法是什么?我的意思是一些活动。
我想可以使用stateflow
,类似的内容:
class MainViewModel : ViewModel() {
init {
val client = CustomWebViewClient()
viewModelScope.launch {
client.onPageFinished.collect {
// ...
}
}
}
}
class CustomWebViewClient() : WebViewClient() {
private val _onPageFinished = MutableStateFlow("")
val onPageFinished = _onPageFinished.asStateFlow()
override fun onPageFinished(view: WebView, url: String) {
_onPageFinished.update { "" }
}
}
但是在这种情况下,需要传输不必要的空字符串,并将在OnPageFineded
之前首先呼叫,因为mutableStateflow < /代码>具有值。因此,出现需要添加一些枚举或类,以便在
关键字时使用进行过滤。
也许有更多最短的方法可以做到这一点?
There is CustomWebViewClient
with override function onPageFinished
. What is the shortest way to notify MainViewModel
about the function triggered? I mean some event.
I suppose that can use StateFlow
, something like this:
class MainViewModel : ViewModel() {
init {
val client = CustomWebViewClient()
viewModelScope.launch {
client.onPageFinished.collect {
// ...
}
}
}
}
class CustomWebViewClient() : WebViewClient() {
private val _onPageFinished = MutableStateFlow("")
val onPageFinished = _onPageFinished.asStateFlow()
override fun onPageFinished(view: WebView, url: String) {
_onPageFinished.update { "" }
}
}
But in this case need to transfer unnecessary empty string and will be occurs first call before onPageFinished
called because MutableStateFlow
has value. So appear required add some enum or class in order to do filter with when
keyword.
Maybe is there more shortest way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您想使用
mutablStateFlow
方法,另一个选项也是覆盖onPagestarted
,并做类似的事情,尽管最终使用FOLLOWS为此是有点过分的夸张,并且使用lambda方法Mieszko Koinma建议的可能更为直接。
If you want to use the
MutablStateFlow
approach, another option is to also overrideonPageStarted
as well and do something likeThough ultimately using flows for this is kinda overkill and using the lambda approach suggested by Mieszko Koźma is probably more straight forward.
您可以将lambda参数添加到CustomWebViewClient构造函数中,该构造器一旦完成后就会被调用。
请注意,引用Android中的任何内容。* ViewModel中的软件包通常是一个很大的无行为。
You can add lambda parameter into CustomWebViewClient constructor that will get called once page is finished.
Please note that referencing anything from android.* package in a ViewModel is most often a big no-go.