如何基于lateinit属性构建实时数据



我有一个初始化较晚的属性。现在我想提供一个实时数据,它在属性完全初始化之前不会发出任何东西。如何以正确的Kotlin方式做到这一点?

class SomeConnection {
val data: Flow<SomeData>
...
class MyViewModel {
private lateinit var _connection: SomeConnection
// private val _connection: CompletableDeferred<SomeConnection>()
val data = _coonection.ensureInitilized().data.toLiveData()
fun connect(){
viewModelScope.launch {
val conn = establishConnection()
// Here I have to do something for the call ensureInitilized to proceed
}
}
private suspend fun establishConnection(){
...
}

声明一个发出SomeConnection类型值的MutableLiveData和相应的LiveData。

private val _connectionLiveData = MutableLiveData<SomeConnection>()
val connectionLiveData: LiveData<SomeConnection> = _connectionLiveData

然后在初始化_connection时为_connectionLiveData赋值:

if (::_connection.isInitialized()) _connectionLiveData.value = _connection

(或者_connectionLiveData.postValue(_connection),如果您的代码同时工作(

现在在代码的另一个地方观察这个LiveData,我将在这里使用片段作为示例:

override fun firstOnViewCreated(view: View, savedInstanceState: Bundle?) {
viewModel.connectionLiveData.observe(this, ::sendData)
}

然后通过相应的视图模型方法发送所需的数据

最新更新