Reputation: 530
I'm trying to learn LiveData. I wrote a sample code to download some API data asynchronously and return it to the MainActivity for being logged. I'm not using ViewModel as I've yet to learn it.
Here's the code for the DownloadInfoClass.kt in which I'm placing the LiveData object:
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
}
}
In the MainActivity.kt class, I'm placing the Observer in the OnCreate method. Here's the code:
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)
})
}
I don't understand why it's not logging the data. Could it because I'm not using a ViewModel? I mean, all the blogs that I've gone through for a solution, each of them has used a ViewModel with LiveData.
Upvotes: 0
Views: 151
Reputation: 157447
you need to post the new value after reading it from the inputstream.
while (data != -1){
val current = data.toChar().toString()
result += current
data = inputStreamReader.read()
}
mutableLiveData.postValue(result)
Upvotes: 2