Android Jetpack

기존 예제 변경

----___<<<<< 2022. 4. 17. 16:41

https://philosopher-chan.tistory.com/1491

 

Retrofit - 2 (Simple Retrofit Example)

 개복치개발자 강의는 아래의 링크에서 확인할 수 있습니다. 개복치개발자 | Linktree uyalae@naver.com linktr.ee  간단한 Retrofit 예제를 한번 해보도록 하겠습니다.  우선적으로 gradle에 implementation을..

philosopher-chan.tistory.com

위의 예제를 조금 변경해보겠습니다.

 

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1")

 

interface MyApi {

//    @GET("posts")
//    suspend fun getPostAll() : List<Post>

    @GET("posts/1")
    suspend fun getPost1() : Post

    @GET("posts/{number}")
    suspend fun getPostNumber(
        @Path("number") number : Int
    ) : Post

}

 

object RetrofitInstance {

    val BASE_URL = "https://jsonplaceholder.typicode.com/"

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

    fun getInstance() : Retrofit {
        return client
    }

}

 

data class Post (
    val userId : Int,
    val id : Int,
    val title : String,
    val body : String
)

 

class MainViewModel : ViewModel() {

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

    private var _mutableWord1 = MutableLiveData<String>()
    val liveWord1 : LiveData<String>
        get() = _mutableWord1


    private var _mutableWord2 = MutableLiveData<String>()
    val liveWord2 : LiveData<String>
        get() = _mutableWord2

    fun getPost1() = viewModelScope.launch {
        val post = retrofitInstance.getPost1()
        _mutableWord1.value = post.title
    }

    fun getPostNumber(number : Int) = viewModelScope.launch {
        val post = retrofitInstance.getPostNumber(number)
        _mutableWord2.value = post.title


    }

}

 

class MainActivity : AppCompatActivity() {

    lateinit var viewModel : MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        viewModel.getPost1()
        viewModel.getPostNumber(2)

        val area1 = findViewById<TextView>(R.id.area1)
        val area2 = findViewById<TextView>(R.id.area2)

        viewModel.liveWord1.observe(this, Observer {
            area1.text = it.toString()
        })

        viewModel.liveWord2.observe(this, Observer {
            area2.text = it.toString()
        })


    }
}

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

Retrofit + ViewModelScope + RecyclerView + Glide Example  (0) 2022.04.20
Retrofit Simple Example RecyclerView 추가  (0) 2022.04.18
Simple Coroutine / ViewModelScope  (0) 2022.04.16
ViewModelScope  (0) 2022.04.13
Retrofit이란?  (0) 2022.04.12