Android如何实现RxJava中throttleFirst⽅法
概述
在指定时间内只执⾏⼀次,类似RxJava中的throttleFirst⽅法,最近在做Android⽹络监控,发现断⽹和连上⽹时,会有回调多次,这样就会导致我们的逻辑被调⽤多次,不合符需求,本来打算⽤RxJava中throttleFirst⽅法做,后来想想还是⾃⼰实现,毕竟也不难;
具体实现:
package bot.utils;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.WorkerThread;
import urrent.locks.Lock;
import urrent.locks.ReentrantLock;
public class BotSingleCallUtil {
private static boolean isTimeIn;//是否还在指定时间内
private static long mTime;//指定的时间,默认2秒
private static Lock mLock = new ReentrantLock();
private static BotSingleCallUtil mThrottleFirst;
private static HandlerThread handlerThread;
private static Handler handler;
private static BotSingleCallUtil initSingleCall() {
if (null == mThrottleFirst) {
try {
mLock.lock();
if (null == mThrottleFirst) {
mThrottleFirst = new BotSingleCallUtil();
android retrofitisTimeIn = true;
mTime = 2000;
handlerThread = new HandlerThread("Manbot WorkThread");
handlerThread.start();//必须得启动线程,要抛NullException
handler = new Looper());
}
} finally {
mLock.unlock();
}
}
return mThrottleFirst;
}
static class MyHandler extends Handler {
public MyHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
isTimeIn = true;
} else if (msg.what == 1) {
Observer observer = (Observer) msg.obj;
observer.callback();
}
}
}
private BotSingleCallUtil setTimeIn(long time) {
this.mTime = time;
return this;
}
/**
* ⼦线程中调⽤
*

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。