0

我有两个片段。一个理想的活动,我使用 nav Host 从第一个片段导航到另一个片段。到目前为止,我还没有数据库。我使用改造在存储库中进行调用,将结果作为密封类的 OutPut 返回,我得到了第一个片段 ViewModel 的 API 调用结果,我可以在第一个片段中观察它。现在我如何将它发送到第二个片段或第二个 ViewModel。这里最好的解决方案是什么?我不想实现数据库。我不想通过为第二个 ViewModel 创建存储库并调用相同的方法来进行另一个调用。如果我正确的话,我还想观察我可以通过 DiffUtil 执行的列表中的任何更改?在这种情况下,最好的解决方案是什么?下面是我的代码。如何在第二个片段适配器中发送 wordResponse 实时数据并观察变化。

我的仓库

class DictionaryRepository internal constructor(private val networkService: NetworkService) {


companion object {
    @Volatile
    private var dictionaryRepoInstance: DictionaryRepository? = null

    fun getInstance(dictionaryService: NetworkService) =
        dictionaryRepoInstance ?: synchronized(this) {
            dictionaryRepoInstance
                ?: DictionaryRepository(dictionaryService).also { dictionaryRepoInstance = it }
        }
}

/**
 * Fetch a new searched word from the network
 */
suspend fun fetchRecentSearchedWord(term: CharSequence) = try {
    val response = networkService.retrofitClient().makeCallForWordDefinition(term)
    OutputResult.Success(response.list)
} catch (t: Throwable) {
    OutputResult.Error(t)
}

}

我的视图模型

class SearchFragmentViewModel internal constructor(
private val dictionaryRepository: DictionaryRepository) : ViewModel() {

/** Show a loading spinner if true*/
private val _spinner = MutableLiveData(false)
val spinner: LiveData<Boolean> get() = _spinner

/**take the data into the result live data*/
private val _wordResponse = MutableLiveData<OutputResult>()
val wordResponse: LiveData<OutputResult> get() = _wordResponse


fun makeAPICallWithSuspendFunction(term: CharSequence) {
    _spinner.value = true
    viewModelScope.launch(Dispatchers.Main) {

        val result = dictionaryRepository.fetchRecentSearchedWord(term)

        _wordResponse.value = when (result) {
            is OutputResult.Success -> {
                OutputResult.Success(result.output)
            }
            is OutputResult.Error -> {
                OutputResult.Error(result.throwable)
            }
        }
    }
    _spinner.value = false
}

}

4

0 回答 0