쏭식
Ssongcode;
쏭식
전체 방문자
오늘
어제
  • 분류 전체보기 (106)
    • JAVA (21)
      • Basic (21)
    • Kotlin (14)
      • Basic (14)
    • Android (64)
      • Basic (24)
      • JETPACK (30)
      • Compose (8)
      • 파고들기 (2)
    • Project (4)
    • etc (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • 변수
  • 알고리즘
  • 상속
  • 메소드
  • Room
  • 코딩테스트
  • 리사이클러뷰
  • ViewModel
  • 코테
  • Kotlin
  • Android
  • 객체지향
  • workmanager
  • 컴포즈
  • 자바
  • 백준
  • Adapter
  • livedata
  • 기초100제
  • AAC
  • 코틀린코테
  • 자료구조
  • 프로젝트회고
  • 배열
  • DataBinding
  • mvvm
  • Jetpack
  • 코드업100제
  • 코틀린
  • compose

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
쏭식

Ssongcode;

[JETPACK개론] Retrofit + ViewModelScope + RV + Glide
Android/JETPACK

[JETPACK개론] Retrofit + ViewModelScope + RV + Glide

2022. 8. 28. 23:59

이 게시물에서는 기존에 진행했던 Retrofit + ViewModel + RV에서 해당 데이터에 이미지를 Glide로 불러오고,

AAC(Android Architecture Components)에 맞게끔 구조를 살짝 변경해보겠다.

출처 : 공식문서

AAC(Android Architecture Components) 는 테스트와 유지보수가 쉬운 앱을 디자인할 수 있도록 돕는 라이브러리의 모음이다.

위의 그림처럼 크게 ViewModel, Repositroy, Room, Retrofit 등이 포함되어 있다.

 

이제 코드를 살펴보자.

패키지구성

먼저 위와 같이 패키지를 분리하여 구성하였고,

object RetrofitInstance {
    val BASE_URL = "https://raw.githubusercontent.com/"

    val clinet = Retrofit
        .Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    fun getInstance() : Retrofit {
        return clinet
    }
}
interface MyApi {
    @GET("googlecodelabs/kotlin-coroutines/master/advanced-coroutines-codelab/sunflower/src/main/assets/plants.json")
    suspend fun getAllPlants() : List<Plant>
}

이렇게 api를 구현하였고,

전 게시물에서는 ViewModel에서 바로 api를 불러왔지만 위의 그림처럼 Repsitory를 통해 불러오는 것으로 변경하였다.

class Repository {

    private val client = RetrofitInstance.getInstance().create(MyApi::class.java)

    suspend fun getAllData() = client.getAllPlants()
}

이렇게 Repsitory를 만들어주어 api를 호출하고 이제 viewModel에서는 retrofitInstance가 아닌, Repsitory를 이용해 호출한다.

class MainViewModel : ViewModel() {

//    val retrofitInstance : MyApi = RetrofitInstance.getInstance().create(MyApi::class.java)

    private val repository = Repository()

    private val _result = MutableLiveData<List<Plant>>()
    val result : LiveData<List<Plant>>
        get() = _result

    fun getAllData() = viewModelScope.launch {
        Log.d("MainViewModel", repository.getAllData().toString())
        _result.value = repository.getAllData()

    }

}

이렇게 Repository에 있는 getAllData를 통해 api에 접근한다!!

class CustomAdapter(val context : Context, val dataSet : List<Plant>) : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    class ViewHolder(view : View) : RecyclerView.ViewHolder(view) {
        val textView : TextView = view.findViewById(R.id.textArea)
        val imageView : ImageView = view.findViewById(R.id.imageArea)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.text_row_item, parent, false)

        return ViewHolder(view)

    }

    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {

        holder.textView.text = dataSet[position].name
        Glide.with(context)
            .load(dataSet[position].imageUrl)
            .into(holder.imageView)

    }

    override fun getItemCount(): Int {
        return dataSet.size
    }

}

리사이클러뷰 어댑터에서는 이와 같이 구현하였고, 여기서 볼 점은 Glide를 통해 해당 dataSet에 있는 imageUrl을 load하여 이미지를 불러온 점이다!

이제 액티비티에서 viewModel의 값을 관찰하여 변경될 때 RV와 어댑터를 연결해주면 끝!!

val viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
viewModel.getAllData()

val rv = findViewById<RecyclerView>(R.id.rv)

viewModel.result.observe(this, Observer {
    val customAdapter = CustomAdapter(this, it)
    rv.adapter = customAdapter
    rv.layoutManager = LinearLayoutManager(this)
})

결과화면

 

 

GitHub - SsongSik/JetPack_Android_Practice: Android practice using the Jetpack library

Android practice using the Jetpack library. Contribute to SsongSik/JetPack_Android_Practice development by creating an account on GitHub.

github.com

 

저작자표시 (새창열림)

'Android > JETPACK' 카테고리의 다른 글

[JETPACK개론] SQLite(2)  (0) 2022.08.30
[JETPACK개론] SQLite(1)  (0) 2022.08.29
[JETPACK개론] Retrofit 예제 + RecyclerView  (0) 2022.08.27
[JETPACK개론] Coroutine / ViewModelScope  (0) 2022.08.26
[JETPACK개론] Retrofit의 CallBack Hell  (0) 2022.08.25
    'Android/JETPACK' 카테고리의 다른 글
    • [JETPACK개론] SQLite(2)
    • [JETPACK개론] SQLite(1)
    • [JETPACK개론] Retrofit 예제 + RecyclerView
    • [JETPACK개론] Coroutine / ViewModelScope
    쏭식
    쏭식

    티스토리툴바