Android 获取ViewModelScope,用于接口(interface)委托(delegate)

标签 android coroutine android-viewmodel kotlin-delegate

我的 viewModel 通过委托(delegate)实现了一个接口(interface),如下所示:

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

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

我根本无法通过 ItemDelegator(viewModelScope, item) 执行 ItemInterface。创建 ViewModel 时,我无法引用 viewModelScope

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

最佳答案

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

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

您还需要修改您的委托(delegate)类,以便您可以在 super ViewModel 构造函数完成执行后将作用域惰性地注入(inject)其中:

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
    }

    ...
}

关于Android 获取ViewModelScope,用于接口(interface)委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66374620/

相关文章:

Android 在应用程序内部模拟 applicationcontext

android - 翻页器控件 - 就像 android 主屏幕

java - Intent 在 recyclerview onclick 中不起作用

Android Wear键盘输入法

android - onCleared 未在 Fragment 的附加 ViewModel 上调用

安卓 : How to write a unit test for fragment depending on a viewmodel Live data attribute?

java - 获取 json user_timeline api twitter 1.1

python-3.x - 如何装饰 asyncio.coroutine 以保留其 __name__?

c# - 以命令模式保存系统

你能在 C 的任何地方 Yield 和 Resume Luajit 协程吗?