Android 获取ViewModelScope以便在接口委托中使用

Android Obtain ViewModelScope so it can be used in interface delegation

我的 viewModel 通过委托实现一个接口,如下所示:

class ProductViewModel(item: Product) : ViewModel(), ItemInterface by ItemDelegator(item)

现在,在 ItemDelegator 中,我需要一个 CoroutineScope 绑定到 ViewModel

我根本做不到ItemInterface by ItemDelegator(viewModelScope, item)。创建 ViewModel 时,我无法引用 viewModelScope

1 - 我能否以某种方式将 viewModelScope 传递给 ItemDelegator 2 - 我的大部分 viewModels 生命周期都绑定到 activity 生命周期。是否可以将 activity lifecycleOwner 传递给 ViewModel(可以从中获取 lifecycleScope)现在,由于它是构造函数中的参数,我可以将它传递给 ItemDelegator?

只有当委托对象是主构造函数的参数时,您才能引用委托对象。通过内联创建它们(像您一样),引用保存在编译期间生成的内部字段中,无法访问。

您可以将主构造函数设为私有并创建将创建委托者的辅助构造函数,因为您不想公开委托初始化。

您还需要修改您的委托器 class 以便您可以在超级 ViewModel 构造函数完成执行后延迟将作用域注入其中:

class ItemDelegator(val item : Product) : ItemInterface {
    lateinit var scope : CoroutineScope

    ...
}

class ProductViewModel private constructor(
    item: Product, 
    private val delegate : ItemDelegator
) : ViewModel(), ItemInterface by delegate {

    constructor(item: Product) : this(ItemDelegator(item))
    init {
        delegate.scope = viewModelScope
    }

    ...
}