提问者:小点点

LiveData不返回更新后的字符串


我在学习生活数据。 我编写了一个示例代码,以异步方式下载一些API数据,并将其返回到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类中,我将观察者放在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? 我的意思是,我看过的所有关于解决方案的博客,每一个都使用了ViewModel和livedata。


共1个答案

匿名用户

您需要在从InputStream中读取新值之后发布它。

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