简体   繁体   中英

Send a parameter to Kotlin retrofit call

I am a beginner in Kotlin. I need to send a variable parameter from my Activity to a Retrofit call.

This is my call in on Create of Detail Activity

override fun onCreate(savedInstanceState: Bundle?) {
    //...
    val id = intent.getStringExtra("id")

    // Get the ViewMode
    val mModel = ViewModelProviders.of(this).get(myObjectViewModel::class.java)

    //Create the observer which updates the UI.
    val myObjectByIdObserver = Observer<MyObject> { myObject->
        //...
    }

    //Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
    mModel.getObjectById.observe(this, myObjectByIdObserver)
}

Here I insert value hardcode, I need the parameter received from the previous Activity.

class MyObjectViewModel : ViewModel() {

    //this is the data that we will fetch asynchronously 
    var myObject: MutableLiveData<MyObject>? = null

    val getMyObjectById: LiveData<MyObject>
        get() {
            if (myObject == null) {
                myObject = MutableLiveData()
                loadMyObjectById()
            }
        return myObject as MutableLiveData<MyObject>
    }

private fun loadMyObjectById() {
    val retrofit = Retrofit.Builder()
        .baseUrl(Api.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val api = retrofit.create(Api::class.java)
    val call = api.myObjectById(100)

    call.enqueue(object : Callback<MyObject> {
        override fun onResponse(call: Call<MyObject>, response: Response<MyObject>) {
            myObject!!.value = response.body()
        }
        override fun onFailure(call: Call<MyObject>, t: Throwable) {
            var tt = t
        }
    })
}

My API:

interface Api {
    companion object {
        const val BASE_URL = "https://.../"
    }

    @GET("myObjects/{id}")
    fun myObjectById(@Path("id") id: Int?): Call<MyObject>
}

You can do this by ``@Query``` annotation.

interface Api {
    companion object {
        const val BASE_URL = "https://.../"
    }

    @GET("myObjects/{id}")
    fun myObjectById(@Path("id") id: Int?, @Query("a_param") aParam: String?): Call<MyObject>
}

Edited. I completely misread your intension.

What you need seems to be ViewModelProvider.NewInstanceFactory like

class MyObjectViewModel(val id: Int): ViewModel() {
    class Factory(val id: Int) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return MyObjectViewModel(id) as T
        }
    }
}

then

    val myViewModel = ViewModelProviders
        .of(this, MyObjectViewModel.Factory(id))
        .get(MyObjectViewModel::class.java)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM