将参数发送给Kotlin改造电话

时间:2019-01-24 02:45:05

标签: android kotlin observable retrofit android-livedata

我是Kotlin的初学者。我需要将来自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)
}

在这里插入值硬编码,我需要从上一个活动中接收到的参数。

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
        }
    })
}

我的API:

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

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

1 个答案:

答案 0 :(得分:1)

您可以通过``@ Query`''注释来完成此操作。

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>
}

已编辑。我完全误解了你的意图。

您所需要的似乎像ViewModelProvider.NewInstanceFactory

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
        }
    }
}

然后

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