简体   繁体   English

BindingAdapter 与协程 scope

[英]BindingAdapter with coroutine scope

I'm not sure if I'm using CoroutineScope properly inside my Binding Adapter function:我不确定我是否在绑定适配器CoroutineScope正确使用了 CoroutineScope:

@BindingAdapter("srcByFileName")
fun setImageViewResource(imageView: ImageView, fileName: String?) {
    if(fileName == null) return

    CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
        val bitmap = ImageStorageManager.getImageFromInternalStorage(imageView.context, fileName)
        withContext(Dispatchers.Main) {
            imageView.setImageBitmap(bitmap)
        }
    }

}

I need to move the fetching of Bitmap to a different thread hence the need of coroutine.我需要将Bitmap的获取移动到不同的线程,因此需要协程。 I'm just wondering if this is the correct way of doing this.我只是想知道这是否是这样做的正确方法。

If you're using Data Binding , then your logic would probably be in your ViewModel , so it's better to pass viewModelScope to the BindingAdapter function.如果您使用的是Data Binding ,那么您的逻辑可能在您的ViewModel中,因此最好将viewModelScope传递给BindingAdapter function。

Just add a third parameter of type CoroutineScope which you can pass from xml layout through the predefined viewModel object.只需添加CoroutineScope类型的第三个参数,您可以从 xml 布局通过预定义的viewModel object 传递。

And in ViewModel , you can just define your scope like this:ViewModel中,您可以像这样定义 scope :

val scope: CoroutineScope
    get() = viewModelScope

And in xml:在 xml 中:

<data>
    <variable
        name="viewModel"
        type="ViewModelType" />
</data>

...

<ImageView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   app:srcByFileName=@{viewModel.src}
   app:coroutineScope="@{viewModel.scope}" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM