Android Jetpack

Coroutine - 4 (Retrofit + Coroutine)

----___<<<<< 2022. 3. 2. 01:22

개복치개발자 강의는 아래의 링크에서 확인할 수 있습니다.

 

개복치개발자 | Linktree

uyalae@naver.com

linktr.ee

 

 이번에는 Retrofit을 ViewModelScope와 함께 사용해보겠습니다.

 

 폴더 구조는 아래와 같고

 

 

  코드는 아래와 같습니다.

 

interface MyApi {
@GET("googlecodelabs/kotlin-coroutines/master/advanced-coroutines-codelab/sunflower/src/main/assets/plants.json")
suspend fun getAllPlants() : List<Plant>
}
view raw MyApi.kt hosted with ❤ by GitHub
object RetrofitInstance {
val BASE_URL = "https://raw.githubusercontent.com/"
val client = Retrofit
.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
fun getInstance() : Retrofit {
return client
}
}
data class Plant (
val plantId: String,
val name: String,
val description: String,
val growZoneNumber: Int,
val wateringInterval: Int,
val imageUrl: String
)
view raw Plant.kt hosted with ❤ by GitHub
class MainViewModel : ViewModel() {
var retrofitInstance : MyApi
private val _result = MutableLiveData<String?>()
val result: LiveData<String?>
get() = _result
init {
retrofitInstance = RetrofitInstance.getInstance().create(MyApi::class.java)
}
fun test() = viewModelScope.launch {
Log.d("MainViewModel", retrofitInstance.getAllPlants().toString())
_result.value = retrofitInstance.getAllPlants().toString()
}
}
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
viewModel.test()
viewModel.result.observe(this, Observer {
Log.d("MainActivity", it.toString())
})
}
}
view raw MainActivity.kt hosted with ❤ by GitHub

'Android Jetpack' 카테고리의 다른 글

WorkManager - 2 (WorkManager Simple Ex)  (0) 2022.03.06
WorkManager - 1 (WorkManager란)  (0) 2022.03.06
Coroutine - 3 (Room + Coroutine)  (1) 2022.02.27
Coroutine - 2 (Dispatchers)  (0) 2022.02.22
Coroutine - 1 (Coroutine이란?)  (0) 2022.02.20