콜백함수 처리방법
java:
public interface JavaCallback<T> {
void onSuccess(T success);
void onFailure(ApiError error);
}
public void TestCall(@NonNull JavaCallback<ClassName> callback) {
callback.onSuccess(new ClassName())
callback.onFailure(new ApiError())
}
사용예는 생략
kotlin example v1:
@Parcelize
data class Result(
val code: Int,
val msg: String?
):Parcelable
fun testCall(success: ((result: Result?) -> Unit)?,
error: ((ApiError)-> Unit)?
) {
success?.invoke(Result(200, "Test Ok"))
error?.invoke(ApiError(-1, "error"))
}
testCall (
success = {
addLog(it.toString())
},
error = {
addLog(it.toString())
})
kotlin example v2:
class KotlinCallback<T> {
var success: ((T) -> Unit) ?= null
var error: ((ApiError)-> Unit) ?= null
}
fun testCall(callback: KotlinCallback<Result>) {
callback.success?.invoke(Result(200, "Test Ok"))
callback.error?.invoke(ApiError(-1, "error"))
}
testCall(
KotlinCallback<Result>().apply {
success = {
addLog(it.toString())
}
error = {
addLog(it.toString())
}
})