簡體   English   中英

使用 viewModelScope.launch 時如何獲得返回結果?

[英]How can I get return result when I use viewModelScope.launch?

我希望得到一個 Int 返回結果,代碼return mDBVoiceRepository.edit(aMVoice)不起作用,我該如何解決?

代碼 A

@Dao
interface DBVoiceDao{
   @Update
   suspend fun edit(aMVoice: MVoice): Int
}


class DBVoiceRepository private constructor(private val mDBVoiceDao: DBVoiceDao){
    suspend fun edit(aMVoice: MVoice):Int{
        return mDBVoiceDao.edit(aMVoice)
    }
}


class HomeViewModel(private val mDBVoiceRepository: DBVoiceRepository) : ViewModel() {
 
    fun edit(aMVoice: MVoice):Int{
        viewModelScope.launch {
           return mDBVoiceRepository.edit(aMVoice)
        }
    }

}

新增內容1:

如果我將結果類型重新設計為LiveData<Int> ,是否有一種簡單的方法?

代碼 B

@Dao
interface DBVoiceDao{
    @Update
    suspend fun edit(aMVoice: MVoice): LiveData<Int>
}


class DBVoiceRepository private constructor(private val mDBVoiceDao: DBVoiceDao){
    suspend fun edit(aMVoice: MVoice): LiveData<Int>{
        return mDBVoiceDao.edit(aMVoice)
    }
}


class HomeViewModel(private val mDBVoiceRepository: DBVoiceRepository) : ViewModel() {

    fun edit(aMVoice: MVoice):LiveData<Int>{
       //How can I do?
    }

}

新增內容2:

我在 Fragment 中運行你的代碼,代碼 C 可以得到正確的結果,而代碼 D 不能得到正確的結果,為什么?

 //Code C
//Return correct ID
binding.button.setOnClickListener {
     val aMVoice = MVoice()
     var id=mHomeViewModel.edit(aMVoice)
     id.observe(viewLifecycleOwner){ rowId-> binding.button.text="ID is: "+ rowId.toString()}
}   

//Code D
//ID value return null
binding.button.setOnClickListener {
   lifecycleScope.launch{
       val aMVoice = MVoice()
       var id=mHomeViewModel.edit(aMVoice)
       binding.button.text="ID is: "+ id.value.toString()
   }
}

如果您無權訪問流,請使用實時數據

fun edit(aMVoice: MVoice):LiveData<Int>{
   val result = MutableLiveData<Int>()
    viewModelScope.launch {
      val data = mDBVoiceRepository.edit(aMVoice)
      result.value = data //or result.postValue(data)
    }
   return result
}

流版本看起來像

suspend fun edit(aMVoice: MVoice):Flow<Int>{
     return flow {
           val data = mDBVoiceRepository.edit(aMVoice)
           emit(data)
     }.flowOn(Dispatchers.IO)
}

您可以使用生命周期Scope.launch在您的活動或片段中收集{ }

編輯

suspend fun edit(aMVoice: MVoice):LiveData<Int>{
   //here return the repository version of the edit
   mDBVoiceRepository.edit(aMVoice)
}

現在上面的設置可以直接在lifecycleScope.launch中的activity或fragment中觀察到{}

或者您可以進行更多修改以刪除暫停合同。

 fun edit(aMVoice: MVoice):LiveData<Int>{
     val result = MutableLiveData<Int>()
      viewModelScope.launch(Dispatchers.IO) {
       //here return the repository version of the edit
       result.value = mDBVoiceRepository.edit(aMVoice).value
      }
     return result
   }

並在沒有協程 scope 的情況下直接在片段或活動中觀察這一點。 如果需要,相應地調整細微的變化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM