使用 Room Persistence 从 SQLite 返回的值未分配给 MutableLiveData

value returned from SQLite using Room Persistence is not being assigned to MutableLiveData

我想计算tablemyTable中所有记录的权重字段之和,我试过:

@Entity(tableName = "myTable")
data class Foo(
    @ColumnInfo(name = "purchaseWeight")
    val weight: Int,
    @ColumnInfo(name = "purchaseDate")
    val date: Long,
    val description: String?

) {

    @PrimaryKey(autoGenerate = true)
    var id: Int = 0

}

和其他class

data class Sum(val sum: Int)

在道中class

@Dao
interface FooDAO {
    @Query("SELECT SUM(purchaseWeight) AS sum FROM myTable")
    suspend fun calculateSumOfAllWeight(): Sum  
}

在存储库中 class

class FooRepository(application: Application) {

    private var fooDAO: FooDAO

    private var sumOfAllWeight = MutableLiveData<Int>()

    init {
        // skipping other code
        CoroutineScope(Dispatchers.IO).launch {
             Log.e(TAG, "Got sum "+ fooDAO.calculateSumOfAllWeight().sum) // Here it prints actual sum of all records
             sumOfAllWeight.postValue(fooDAO.calculateSumOfAllWeight().sum) // but here value is never assigned to MutableLiveData<Int> which is sumOfAllWeight variable
        }
    }

    fun getSumOfAllWeight(): MutableLiveData<Int> {    
        Log.e(TAG, " sumOfAllWeight "+ sumOfAllWeight.value) // it prints null
        return sumOfAllWeight    
    }    
}

ViewModel class 是:

class FooViewModel(
    application: Application
): AndroidViewModel(application) {

    private var repository = FooRepository(application) 

    fun getSumOfAllWeight():MutableLiveData<Int> {
        return repository.getSumOfAllWeight()
    }
}

和MainActivity.kt是:

class MainActivity : AppCompatActivity(){

    private lateinit var mFooViewModel: FooViewModel

    private var sumOfAllWeight = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        mFooViewModel = ViewModelProviders.of(this).get(FooViewModel::class.java)

        mFooViewModel.getSumOfAllWeight().observe(
            this,
            Observer {
                sumOfAllWeight = it
            }
        )

        // Set Values to top TextViews
        tv_sum_lbl.text =   "$sumOfAllWeight - KG(s)"  // Here  is set to this view          
    }
}

但它打印

E/SUM_OF_WEIGHT: sumOfAllWeight null
E/SUM_OF_WEIGHT: Got sum 324

无法弄清楚为什么没有将 sumOfAllWeight.postValue(fooDAO.calculateSumOfAllWeight().sum) 的值分配给 MutableLiveData<Int>

在您的 activity sumOfAllWeight 内部无法观察到。所以它不会反映 observer 之外的变化。使用以下代码检查:

mFooViewModel.getSumOfAllWeight().observe(
    this,
    Observer {
        tv_sum_lbl.text =   "$it - KG(s)" // Now check value here
    }
)