T
05/28/2020, 12:41 PMprivate const val BASE_URL = "<https://newsapi.org/v2/>"
private const val API_KEY = "1234"
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
private val retrofit = Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create())
.baseUrl(BASE_URL)
.build()
interface NewsApiService {
@GET("top-headlines?country=us&apiKey=${API_KEY}")
fun getProperties():
Call<String>
}
object NewsApi {
val retrofitService : NewsApiService by lazy {
retrofit.create(NewsApiService::class.java) }
}
class NewsViewModel : ViewModel() {
// The internal MutableLiveData String that stores the most recent response
private val _response = MutableLiveData<String>()
// The external immutable LiveData for the response String
val response: LiveData<String>
get() = _response
/**
* Call getNewsData() on init so we can display status immediately.
*/
init {
getNewsData()
}
/**
* Sets the value of the status LiveData to the News API status.
*/
private fun getNewsData() {
_response.value = NewsApi.retrofitService.getProperties().enqueue(
object: Callback<String> {
override fun onFailure(call: Call<String>, t: Throwable){
_response.value = "Failure: " + t.message
}
override fun onResponse(call: Call<String>, response: Response<String>) {
_response.value = response.body()
}
}).toString()
}
}T
05/28/2020, 12:45 PMallan.conda
05/28/2020, 12:56 PMjw
05/28/2020, 1:03 PM@Json, annotate the endpoint with @Json and have its body type as String, in a custom converter match on both the type == String::class.java and the annotations array contains an instance of Json::class.java and then just call ResponseBody.string() and return it.jw
05/28/2020, 1:04 PMString and it'll do exactly the same thingjw
05/28/2020, 1:04 PMResponseBody as your type and call string() yourselfT
05/28/2020, 3:41 PMT
05/28/2020, 3:42 PMT
05/28/2020, 3:51 PM