簡體   English   中英

BindingAdapter 與協程 scope

[英]BindingAdapter with coroutine scope

我不確定我是否在綁定適配器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)
        }
    }

}

我需要將Bitmap的獲取移動到不同的線程,因此需要協程。 我只是想知道這是否是這樣做的正確方法。

如果您使用的是Data Binding ,那么您的邏輯可能在您的ViewModel中,因此最好將viewModelScope傳遞給BindingAdapter function。

只需添加CoroutineScope類型的第三個參數,您可以從 xml 布局通過預定義的viewModel object 傳遞。

ViewModel中,您可以像這樣定義 scope :

val scope: CoroutineScope
    get() = viewModelScope

在 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