热传递值抛出 onSuccess 响应可运行?

Hot to pass values throw a onSuccess response runnable?

所以我的目标就像标题所说的那样是传递 API 响应结果将 onSuccess.run() 方法抛给一个片段。只是为了提供一些背景信息,我开始在 Manager class 中执行这样的方法,例如:

    override fun callUser(onSuccess:Runnable, onFailure:Runnable){

 NetworkManager.instance.performCall(NetworkManager.REGISTRATION.verifyUser(id),
                object : NetworkManager.OnRequestCallback<UserInfoResponse> {
                    override fun onSuccess(body: UserInfoResponse?) {
                        body?.data?.let {
                            onSuccess.run()
                        }
                    }

                    override fun onError(errorBody: String?) {
                        onFailure.run()
                    }
                })
    }

然后我转到一个片段并像这样调用上面的方法:

objectManager.callVerifyAdvisor(
                    Runnable {[On Success stuff },
                    Runnable {[On Error]}
        }

问题是,虽然我可以在片段中决定我想在 onSuccess()onFailure() 方法中执行的操作,但我无法获得该片段的 API Results通过这样做。

所以我的想法是做类似的事情[我使用注释来指定重要的部分]:

NetworkManager.instance.performCall(NetworkManager.REGISTRATION.verifyUser(id),
                    object : NetworkManager.OnRequestCallback<UserInfoResponse> {
                        override fun onSuccess(body: UserInfoResponse?) {
                            body?.data?.let {
                                it.userName // I get this from api response
                                onSuccess.run()
                            }
                        }

                        override fun onError(errorBody: String?) {
                            onFailure.run()
                        }
                    })
        }

然后在我的片段上我想要这样的东西:

   objectManager.callVerifyAdvisor(
              Runnable {[On Success stuff }, //receive here the it.userName
              Runnable {[On Error]}
}

有人可以给出任何想法如何做到这一点吗?旁注 -> 我将 kotlin 放在标签上,因为它具有某种功能性的东西。

您只需将 onSuccess 从 Runnable 替换为自定义函数类型回调:

override fun callUser(onSuccess: (String) -> Unit, onFailure: Runnable) {...

然后将用户名传递给回调:

NetworkManager.instance.performCall(NetworkManager.REGISTRATION.verifyUser(id),
                object : NetworkManager.OnRequestCallback<UserInfoResponse> {
                    override fun onSuccess(body: UserInfoResponse?) {
                        body?.data?.let {
                            onSuccess.invoke(it.userName) // Pass userName
                        }
                    }

                    override fun onError(errorBody: String?) {
                        onFailure.run()
                    }
                })
    }

然后你可以从这个回调中得到用户名:

objectManager.callVerifyAdvisor(
          {userName -> } // Here you get your result
          Runnable {[On Error]}
}