API通信を行う関数(以下)を作成しました。
kotlin
1 // API通信(POST) 2 fun conAPI(url: String, req:dtLoginRequest , onSuccess: (json: JSONObject) -> Unit, onFailed: () -> Unit) { 3 4 val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build() 5 val requestAdapter = moshi.adapter(dtLoginRequest::class.java) 6 val header: HashMap<String, String> = hashMapOf("Content-Type" to "application/json") 7 8 Fuel.post(url).header(header).body(requestAdapter.toJson(req)) 9 10 .responseJson() { request, response, result -> 11 12 when (result) { 13 is Result.Success -> { 14 try { 15 onSuccess.invoke(result.value.obj()) 16 } catch (e: Exception) { 17 onFailed.invoke() 18 } 19 20 } 21 is Result.Failure -> { 22 println(result) 23 onFailed.invoke() 24 } 25 } 26 } 27 }
第二引数 req は自作したdata classです。
上記のコードで確かにAPI通信を行えるのですが、
引数がdtLoginRequest固定になっているため他のAPI通信をする場合
同じコードを複数書くことになってしまいます。
どうにかして汎用性の高いコードにしたいと考えているのですがどのようにすれば良いでしょうか?
ご回答よろしくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/17 03:43