Last active
December 4, 2020 03:37
-
-
Save CaiJingLong/bba6fdba52e95f3bcbe1558f9d7c234f to your computer and use it in GitHub Desktop.
Flutter 调用以及返回的封装, 防止重复返回, 有锁版, 防止多线程重复返回的可能
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.os.Handler | |
import android.os.Looper | |
import io.flutter.plugin.common.MethodCall | |
import io.flutter.plugin.common.MethodChannel | |
import java.util.concurrent.locks.ReentrantLock | |
import kotlin.concurrent.withLock | |
/// create 2019-11-27 by cai | |
class ReplyHandler(val call: MethodCall, private val result: MethodChannel.Result?) { | |
companion object { | |
val handler = Handler(Looper.getMainLooper()) | |
} | |
private var isReply = false | |
private val lock = ReentrantLock() | |
fun success(any: Any?) { | |
run { | |
result?.success(any) | |
} | |
} | |
fun error(code: String, detail: String? = null, error: Any? = null) { | |
run { | |
result?.error(code, detail, error) | |
} | |
} | |
fun notImplemented() { | |
run { | |
result?.notImplemented() | |
} | |
} | |
private inline fun run(crossinline runnable: () -> Unit) { | |
lock.withLock { | |
if (isReply) { | |
return | |
} | |
isReply = true | |
handler.post { | |
runnable() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment