LiveData 没有 Return 更新的字符串

LiveData Doesn't Return The Updated String

我正在尝试学习 LiveData。我编写了一个示例代码来异步下载一些 API 数据并将其 return 到 MainActivity 以供记录。我没有使用 ViewModel,因为我还没有学习它。

这是 DownloadInfoClass.kt 的代码,我将在其中放置 LiveData 对象:

package com.example.kotlincurrency

import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.InputStreamReader
import java.lang.Exception
import java.net.HttpURLConnection
import java.net.URL

class DownloadParseInfoClass {

    private var mutableLiveData: MutableLiveData<String> = MutableLiveData()
    private var result: String = ""

    fun downloadMethod(urls: String) = CoroutineScope(Main).launch {
        result = infoDownloadMethod(urls)
    }

    private suspend fun infoDownloadMethod(urls: String): String{
        var result = ""

        withContext(IO){
            try {
                val url = URL(urls)
                val httpURLConnection = url.openConnection() as HttpURLConnection
                val inputStream = httpURLConnection.inputStream
                val inputStreamReader = InputStreamReader(inputStream)

                var data: Int = inputStreamReader.read()
                while (data != -1){
                    val current = data.toChar().toString()
                    result += current
                    data = inputStreamReader.read()
                }
            }

            catch (e: Exception){
                e.printStackTrace()
            }
        }

        return result
    }

    fun getMutableLiveData(): MutableLiveData<String>{
        mutableLiveData.value = result
        return mutableLiveData
    }

}

MainActivity.kt class 中,我将 Observer 放在 OnCreate 方法中。这是代码:

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

        val downloadParseInfoClass = DownloadParseInfoClass()
        downloadParseInfoClass.downloadMethod("https://api.exchangeratesapi.io/latest?base=INR")
        downloadParseInfoClass.getMutableLiveData().observe(this, Observer {
            Log.i("Result", it)
        })
    }

我不明白为什么它不记录数据。可能是因为我没有使用 ViewModel 吗?我的意思是,我浏览过所有寻求解决方案的博客,每个博客都使用了带有 LiveData 的 ViewModel。

您需要 post 从输入流读取新值后。

while (data != -1){
     val current = data.toChar().toString()
     result += current
     data = inputStreamReader.read()
} 
mutableLiveData.postValue(result)