Код: Выделить всё
ProductService.ktКод: Выделить всё
interface ProductService {
@GET("product")
suspend fun getAllProducts(): Response
@GET("product/{pId}")
suspend fun getProductById(@Path("pId") pId: Int): Response
@POST("product")
suspend fun createNewProduct(@Body post: POST): POST
}
< /code>
WPAPI.ktКод: Выделить всё
//retrofit & moshi setup
val moshi: Moshi = Moshi.Builder().add(com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory()).build()
val logging = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
val client = OkHttpClient.Builder()
.addInterceptor(logging)
.build()
object WPAPI {
val retrofitService : ProductService by lazy {
Retrofit.Builder()
.baseUrl("http://[redacted]:8080/api/")
.addConverterFactory(MoshiConverterFactory.create(moshi)) //converter to use to parse the response
.client(client)
.build()
.create(ProductService::class.java) //class to use in order to construct the API service
}
}
< /code>
getAllProducts()Код: Выделить всё
ProductViewModel.ktКод: Выделить всё
fun getAllProducts() : LiveData {
val result = MutableLiveData()
viewModelScope.launch {
val response: Response = try {
WPAPI.retrofitService.getAllProducts()
} catch (e: IOException) {
Log.e("ProductViewModel", "IOException", e)
return@launch
} catch (e: HttpException) {
Log.e("ProductViewModel", "HttpException", e)
return@launch
} catch (e: Exception) {
Log.wtf("ProductViewModel", "Exception", e)
return@launch
}
if (response.isSuccessful && response.body() != null) {
Log.i("ProductViewModel", "Response is good")
result.postValue(response.body()!!)
}
}
return result
}
< /code>
The viewmodel's function is being called from MainActivity as follows:
val productsDBList : List
= viewModel.getAllProducts().value!!
< /code>
Stepping through the debugger when inside the ProductViewModel just jumps from WPAPI.retrofitService.getAllProducts()val response: Response = try {
WPAPI.retrofitService.getAllProducts()
} catch (e: IOException) {
Log.e("ProductViewModel", "IOException", e)
return@launch
} catch (e: HttpException) {
Log.e("ProductViewModel", "HttpException", e)
return@launch
} catch (e: Exception) {
Log.wtf("ProductViewModel", "Exception", e)
return@launch
}
if (response.isSuccessful && response.body() != null) {
Log.i("LifecycleScope", "Response is good")
val pAdapter = ProductAdapter(response.body()!!)
productsRecView.adapter = pAdapter
productsRecView.layoutManager= LinearLayoutManager(this@MainActivity)
}
}
< /code>
Can someone point me to the right direction? I know I'm probably missing something obvious here.
Подробнее здесь: https://stackoverflow.com/questions/796 ... cyclescope
Мобильная версия