EventBus 3.0進(jìn)階:源碼及其設(shè)計(jì)模式 完全解析

前言

在上一篇文章:EventBus 3.0初探: 入門使用及其使用 完全解析中,筆者為大家介紹了EventBus 3.0的用法,相信大家對(duì)其的使用也比較熟悉了侧戴。我們學(xué)習(xí)使用一個(gè)開(kāi)源庫(kù)估盘,不但要知道其怎么使用,也要對(duì)其的實(shí)現(xiàn)原理有一定的熟悉剔氏,學(xué)習(xí)并借鑒它優(yōu)秀的實(shí)現(xiàn)思想塑猖,這樣對(duì)我們以后的開(kāi)發(fā)又或者是自己的開(kāi)源項(xiàng)目都有很大的意義。那么今天的文章谈跛,就是EventBus 3.0的進(jìn)階羊苟,剖析它的實(shí)現(xiàn)原理以及對(duì)其使用的設(shè)計(jì)模式進(jìn)行解析。

本文導(dǎo)讀

由于EventBus較為復(fù)雜感憾,因此本文也相當(dāng)長(zhǎng)蜡励,所以本文分為以下幾個(gè)部分:創(chuàng)建、注冊(cè)凉倚、發(fā)送事件兼都、關(guān)于粘性事件的解析、以及最后的思考稽寒。讀者可以有選擇性地選取某部分來(lái)進(jìn)行閱讀扮碧。

實(shí)現(xiàn)原理

創(chuàng)建

上一篇文章提到,要想注冊(cè)成為訂閱者瓦胎,必須在一個(gè)類中調(diào)用如下:

EventBus.getDefault().register(this);

那么芬萍,我們看一下getDefault()的源碼是怎樣的,EventBus#getDefault()

public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
}

可以看出搔啊,這里使用了單例模式柬祠,而且是雙重校驗(yàn)的單例,確保在不同線程中也只存在一個(gè)EvenBus的實(shí)例负芋。

單例模式:一個(gè)類有且僅有一個(gè)實(shí)例漫蛔,并且自行實(shí)例化向整個(gè)系統(tǒng)提供。

然而旧蛾,我們看看EventBus的構(gòu)造方法:

/** 
  * Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a 
  * central bus, consider {@link #getDefault()}.
  */
public EventBus() {
    this(DEFAULT_BUILDER);
}

它的構(gòu)造方法并沒(méi)有設(shè)置成私有的莽龟!這是為什么?從注解我們看到锨天,每一個(gè)EventBus都是獨(dú)立地毯盈、處理它們自己的事件,因此可以存在多個(gè)EventBus病袄,而通過(guò)getDefault()方法獲取的實(shí)例搂赋,則是它已經(jīng)幫我們構(gòu)建好的EventBus,是單例益缠,無(wú)論在什么時(shí)候通過(guò)這個(gè)方法獲取的實(shí)例都是同一個(gè)實(shí)例脑奠。除此之外,我們可以通過(guò)建造者幫我們建造具有不同功能的EventBus幅慌。
我們繼續(xù)看上面的this(DEFAULT_BUILDER)調(diào)用了另一個(gè)構(gòu)造方法:

  EventBus(EventBusBuilder builder) {
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
    backgroundPoster = new BackgroundPoster(this);
    asyncPoster = new AsyncPoster(this);
    //一系列的builder賦值
}

可以看出宋欺,對(duì)成員變量進(jìn)行了一系列的初始化,那么我們來(lái)看看幾個(gè)關(guān)鍵的成員變量:

private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;
private final Map<Class<?>, Object> stickyEvents;

subscriptionsByEventType:以event(即事件類)為key胰伍,以訂閱列表(Subscription)為value齿诞,事件發(fā)送之后,在這里尋找訂閱者,而Subscription又是一個(gè)CopyOnWriteArrayList骂租,這是一個(gè)線程安全的容器掌挚。你們看會(huì)好奇,Subscription到底是什么菩咨,其實(shí)看下去就會(huì)了解的,現(xiàn)在先提前說(shuō)下:Subscription是一個(gè)封裝類,封裝了訂閱者抽米、訂閱方法這兩個(gè)類特占。
typesBySubscriber:以訂閱者類為key,以event事件類為value云茸,在進(jìn)行register或unregister操作的時(shí)候是目,會(huì)操作這個(gè)map。
stickyEvents:保存的是粘性事件标捺,粘性事件上一篇文章有詳細(xì)描述懊纳。
回到EventBus的構(gòu)造方法,接下來(lái)實(shí)例化了三個(gè)Poster亡容,分別是mainThreadPoster嗤疯、backgroundPoster、asyncPoster等闺兢,這三個(gè)Poster是用來(lái)處理粘性事件的茂缚,我們下面會(huì)展開(kāi)講述。接著屋谭,就是對(duì)builder的一系列賦值了脚囊,這里使用了建造者模式硕淑。

建造者模式:將一個(gè)復(fù)雜對(duì)象的構(gòu)造與它的表示分離熟呛,使同樣的構(gòu)建過(guò)程可以創(chuàng)建不同的表示。

這里的建造者是EventBusBuilder蔗崎,它的一系列方法用于配置EventBus的屬性我擂,使用getDefault()方法獲取的實(shí)例衬以,會(huì)有著默認(rèn)的配置,上面說(shuō)過(guò)扶踊,EventBus的構(gòu)造方法是公有的泄鹏,所以我們可以通過(guò)給EventBusBuilder設(shè)置不同的屬性,進(jìn)而獲取有著不同功能的EventBus秧耗。那么我們來(lái)列舉幾個(gè)常用的屬性加以講解:

//默認(rèn)地备籽,EventBus會(huì)考慮事件的超類,即事件如果繼承自超類分井,那么該超類也會(huì)作為事件發(fā)送給訂閱者车猬。
//如果設(shè)置為false,則EventBus只會(huì)考慮事件類本身尺锚。
boolean eventInheritance = true;
public EventBusBuilder eventInheritance(boolean eventInheritance) {
    this.eventInheritance = eventInheritance;
    return this;
}

//當(dāng)訂閱方法是以onEvent開(kāi)頭的時(shí)候珠闰,可以調(diào)用該方法來(lái)跳過(guò)方法名字的驗(yàn)證,訂閱這類會(huì)保存在List中
List<Class<?>> skipMethodVerificationForClasses;
public EventBusBuilder skipMethodVerificationFor(Class<?> clazz) {
    if (skipMethodVerificationForClasses == null) {
        skipMethodVerificationForClasses = new ArrayList<>();
    }
    skipMethodVerificationForClasses.add(clazz);
    return this;
}

//更多的屬性配置請(qǐng)參考源碼瘫辩,均有注釋
//...

那么伏嗜,我們通過(guò)建造者模式來(lái)手動(dòng)創(chuàng)建一個(gè)EventBus坛悉,而不是使用getDefault()方法:

EventBus eventBus = EventBus.builder()
        .eventInheritance(false)
        .sendNoSubscriberEvent(true)
        .skipMethodVerificationFor(MainActivity.class)
        .build();

注冊(cè)

好了,以上說(shuō)了一大推關(guān)于EventBus的創(chuàng)建承绸,接下來(lái)裸影,我們繼續(xù)講它的注冊(cè)過(guò)程。要想使一個(gè)類成為訂閱者军熏,那么這個(gè)類必須有一個(gè)訂閱方法轩猩,以@Subscribe注解標(biāo)記的方法,接著調(diào)用register()方法來(lái)進(jìn)行注冊(cè)荡澎。那么我們直接來(lái)看EventBus#register()均践。

register

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

先獲取了訂閱者類的class,接著交給SubscriberMethodFinder.findSubscriberMethods()處理摩幔,返回結(jié)果保存在List<SubscriberMethod>中彤委,由此可推測(cè)通過(guò)上面的方法把訂閱方法找出來(lái)了,并保存在集合中热鞍,那么我們直接看這個(gè)方法葫慎,SubscriberMethodFinder#findSubscriberMethods()

findSubscriberMethods

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    //首先從緩存中取出subscriberMethodss薇宠,如果有則直接返回該已取得的方法
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    //從EventBusBuilder可知偷办,ignoreGenerateIndex一般為false
    if (ignoreGeneratedIndex) {
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        subscriberMethods = findUsingInfo(subscriberClass);
    }
    if (subscriberMethods.isEmpty()) {
        throw new EventBusException("Subscriber " + subscriberClass
                + " and its super classes have no public methods with the @Subscribe annotation");
    } else {
        //將獲取的subscriberMeyhods放入緩存中
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    }
}

從上面的邏輯可以知道,一般會(huì)調(diào)用findUsingInfo方法澄港,我們接著看SubscriberMethodFinder#findUsingInfo方法:

findUsingInfo

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    //準(zhǔn)備一個(gè)FindState椒涯,該FindState保存了訂閱者類的信息
    FindState findState = prepareFindState();
    //對(duì)FindState初始化
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        //獲得訂閱者的信息,一開(kāi)始會(huì)返回null
        findState.subscriberInfo = getSubscriberInfo(findState);
        if (findState.subscriberInfo != null) {
            SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
            for (SubscriberMethod subscriberMethod : array) {
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
        } else {
            //1 回梧、到了這里
            findUsingReflectionInSingleClass(findState);
        }
        //移動(dòng)到父類繼續(xù)查找
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

上面用到了FindState這個(gè)內(nèi)部類來(lái)保存訂閱者類的信息废岂,我們看看它的內(nèi)部結(jié)構(gòu):

FindState

static class FindState {
    //訂閱方法的列表
    final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
    //以event為key,以method為value
    final Map<Class, Object> anyMethodByEventType = new HashMap<>();
    //以method的名字生成一個(gè)method為key狱意,以訂閱者類為value
    final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
    final StringBuilder methodKeyBuilder = new StringBuilder(128);

    Class<?> subscriberClass;
    Class<?> clazz;
    boolean skipSuperClasses;
    SubscriberInfo subscriberInfo;

    //對(duì)FindState初始化
    void initForSubscriber(Class<?> subscriberClass) {
        this.subscriberClass = clazz = subscriberClass;
        skipSuperClasses = false;
        subscriberInfo = null;
    }

    //省略...
}

可以看出湖苞,該內(nèi)部類保存了訂閱者及其訂閱方法的信息,用Map一一對(duì)應(yīng)進(jìn)行保存详囤,接著利用initForSubscriber進(jìn)行初始化财骨,這里subscriberInfo初始化為null,因此在SubscriberMethodFinder#findUsingInfo里面藏姐,會(huì)直接調(diào)用到①號(hào)代碼隆箩,即調(diào)用SubscriberMethodFinder#findUsingReflectionInSingleClass,這個(gè)方法非常重要8嵫睢0齐!在這個(gè)方法內(nèi)部兜材,利用反射的方式理澎,對(duì)訂閱者類進(jìn)行掃描逞力,找出訂閱方法,并用上面的Map進(jìn)行保存矾端,我們來(lái)看這個(gè)方法掏击。

findUsingReflectionInSingleClass

  private void findUsingReflectionInSingleClass(FindState findState) {
    Method[] methods;
    try {
        // This is faster than getMethods, especially when subscribers are fat classes like Activities
        methods = findState.clazz.getDeclaredMethods();
    } catch (Throwable th) {
        // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
        methods = findState.clazz.getMethods();
        findState.skipSuperClasses = true;
    }
    for (Method method : methods) {
        //獲取方法的修飾符
        int modifiers = method.getModifiers();
        if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            //獲取方法的參數(shù)類型
            Class<?>[] parameterTypes = method.getParameterTypes();
            //如果參數(shù)個(gè)數(shù)為一個(gè),則繼續(xù)
            if (parameterTypes.length == 1) {
                //獲取該方法的@Subscribe注解
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
                    //參數(shù)類型 即為 事件類型
                    Class<?> eventType = parameterTypes[0];
                    // 2 秩铆、調(diào)用checkAdd方法
                    if (findState.checkAdd(method, eventType)) {
                        //從注解中提取threadMode
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        //新建一個(gè)SubscriberMethod對(duì)象,并添加到findState的subscriberMethods這個(gè)集合內(nèi)
                        findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                    }
                }
            //如果開(kāi)啟了嚴(yán)格驗(yàn)證灯变,同時(shí)當(dāng)前方法又有@Subscribe注解殴玛,對(duì)不符合要求的方法會(huì)拋出異常
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException("@Subscribe method " + methodName +
                        "must have exactly 1 parameter but has " + parameterTypes.length);
            }
        } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
            String methodName = method.getDeclaringClass().getName() + "." + method.getName();
            throw new EventBusException(methodName +
                    " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
        }
    }
}

雖然該方法比較長(zhǎng),但是邏輯非常清晰添祸,逐一判斷訂閱者類是否存在訂閱方法滚粟,如果符合要求,并且②號(hào)代碼調(diào)用FindState#checkAdd方法返回true的時(shí)候,才會(huì)把方法保存在findState的subscriberMethods內(nèi)刃泌。而SubscriberMethod則是用于保存訂閱方法的一個(gè)類凡壤。那么我們來(lái)看看FindState#checkAdd做了什么工作。

checkAdd

boolean checkAdd(Method method, Class<?> eventType) {
    // 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
    // Usually a subscriber doesn't have methods listening to the same event type.
    Object existing = anyMethodByEventType.put(eventType, method);
    if (existing == null) {
        return true;
    } else {
        if (existing instanceof Method) {
            if (!checkAddWithMethodSignature((Method) existing, eventType)) {
                // Paranoia check
                throw new IllegalStateException();
            }
            // Put any non-Method object to "consume" the existing Method
            anyMethodByEventType.put(eventType, this);
        }
        return checkAddWithMethodSignature(method, eventType);
    }
}

從注釋可知耙替,這里包含兩重檢驗(yàn)亚侠,第一層檢驗(yàn)是判斷eventType的類型,而第二次檢驗(yàn)是判斷方法的完整簽名俗扇。首先通過(guò)anyMethodByEventType.put(eventType, method) 將eventType以及method放進(jìn)anyMethodByEventType這個(gè)Map中(上面提到),同時(shí)該put方法會(huì)返回同一個(gè)key的上一個(gè)value值硝烂,所以如果之前沒(méi)有別的方法訂閱了該事件,那么existing應(yīng)該為null铜幽,可以直接返回true滞谢;否則為某一個(gè)訂閱方法的實(shí)例,要進(jìn)行下一步的判斷除抛。接著往下走狮杨,會(huì)調(diào)用checkAddWithMethodSignature()方法。

checkAddWithMethodSignature

private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
    methodKeyBuilder.setLength(0);
    methodKeyBuilder.append(method.getName());
    methodKeyBuilder.append('>').append(eventType.getName());

    //methodKey由方法名與事件名組成
    String methodKey = methodKeyBuilder.toString();
    //獲取當(dāng)前方法所在的類的類名
    Class<?> methodClass = method.getDeclaringClass();
    //給subscriberClassByMethodKey賦值到忽,并返回上一個(gè)相同key的 類名
    Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
    if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
        // Only add if not already found in a sub class
        return true;
    } else {
        // Revert the put, old class is further down the class hierarchy
        subscriberClassByMethodKey.put(methodKey, methodClassOld);
        return false;
    }
}

從上面的代碼看出橄教,該方法首先獲取了當(dāng)前方法的methodKey、methodClass等绘趋,并賦值給subscriberClassByMethodKey颤陶,如果方法簽名相同,那么返回舊值給methodClassOld陷遮,接著是一個(gè)if判斷滓走,判斷methodClassOld是否為空,由于第一次調(diào)用該方法的時(shí)候methodClassOld肯定是null帽馋,此時(shí)就可以直接返回true了搅方。但是比吭,后面還有一個(gè)判斷即methodClassOld.isAssignableFrom(methodClass),這個(gè)的意思是:methodClassOld是否是methodClass的父類或者同一個(gè)類姨涡。如果這兩個(gè)條件都不滿足衩藤,則會(huì)返回false,那么當(dāng)前方法就不會(huì)添加為訂閱方法了涛漂。

那么赏表,說(shuō)了一大堆關(guān)于checkAddcheckAddWithMethodSignature方法的源碼,那么這兩個(gè)方法到底有什么作用呢匈仗?從這兩個(gè)方法的邏輯來(lái)看瓢剿,第一層判斷根據(jù)eventType來(lái)判斷是否有多個(gè)方法訂閱該事件,而第二層判斷根據(jù)完整的方法簽名(包括方法名字以及參數(shù)名字)來(lái)判斷悠轩。下面是筆者的理解:

第一種情況:比如一個(gè)類有多個(gè)訂閱方法间狂,方法名不同,但它們的參數(shù)類型都是相同的(雖然一般不這樣寫火架,但不排除這樣的可能)鉴象,那么遍歷這些方法的時(shí)候,會(huì)多次調(diào)用到checkAdd方法何鸡,由于existing不為null纺弊,那么會(huì)進(jìn)而調(diào)用checkAddWithMethodSignature方法,但是由于每個(gè)方法的名字都不同音比,因此methodClassOld會(huì)一直為null俭尖,因此都會(huì)返回true。也就是說(shuō)洞翩,允許一個(gè)類有多個(gè)參數(shù)相同的訂閱方法稽犁。

第二種情況:類B繼承自類A,而每個(gè)類都是有相同訂閱方法骚亿,換句話說(shuō)已亥,類B的訂閱方法繼承并重寫自類A,它們都有著一樣的方法簽名来屠。方法的遍歷會(huì)從子類開(kāi)始虑椎,即B類,在checkAddWithMethodSignature方法中俱笛,methodClassOld為null捆姜,那么B類的訂閱方法會(huì)被添加到列表中。接著迎膜,向上找到類A的訂閱方法泥技,由于methodClassOld不為null而且顯然類B不是類A的父類,methodClassOld.isAssignableFrom(methodClass)也會(huì)返回false磕仅,那么會(huì)返回false珊豹。也就是說(shuō)簸呈,子類繼承并重寫了父類的訂閱方法,那么只會(huì)把子類的訂閱方法添加到訂閱者列表店茶,父類的方法會(huì)忽略蜕便。

讓我們回到findUsingReflectionInSingleClass方法,當(dāng)遍歷完當(dāng)前類的所有方法后贩幻,會(huì)回到findUsingInfo方法轿腺,接著會(huì)執(zhí)行最后一行代碼,即return getMethodsAndRelease(findState);那么我們繼續(xù)看SubscriberMethodFinder#getMethodsAndRelease方法丛楚。

getMethodsAndRelease

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
    //從findState獲取subscriberMethods吃溅,放進(jìn)新的ArrayList
    List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
    //把findState回收
    findState.recycle();
    synchronized (FIND_STATE_POOL) {
        for (int i = 0; i < POOL_SIZE; i++) {
            if (FIND_STATE_POOL[i] == null) {
                FIND_STATE_POOL[i] = findState;
                break;
            }
        }
    }
    return subscriberMethods;
}

通過(guò)該方法,把subscriberMethods不斷逐層返回鸯檬,直到返回EventBus#register()方法,最后開(kāi)始遍歷每一個(gè)訂閱方法螺垢,并調(diào)用subscribe(subscriber, subscriberMethod)方法喧务,那么,我們繼續(xù)來(lái)看EventBus#subscribe方法枉圃。

subscribe

在該方法內(nèi)功茴,主要是實(shí)現(xiàn)訂閱方法與事件直接的關(guān)聯(lián),即注冊(cè)孽亲,即放進(jìn)我們上面提到關(guān)鍵的幾個(gè)Map中:subscriptionsByEventType坎穿、typesBySubscriber、stickyEvents返劲。

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    //將subscriber和subscriberMethod封裝成 Subscription
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    //根據(jù)事件類型獲取特定的 Subscription
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    //如果為null玲昧,說(shuō)明該subscriber尚未注冊(cè)該事件
    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<>();
        subscriptionsByEventType.put(eventType, subscriptions);
    } else {
        //如果不為null,并且包含了這個(gè)subscription 那么說(shuō)明該subscriber已經(jīng)注冊(cè)了該事件篮绿,拋出異常
        if (subscriptions.contains(newSubscription)) {
            throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                    + eventType);
        }
    }

    //根據(jù)優(yōu)先級(jí)來(lái)設(shè)置放進(jìn)subscriptions的位置孵延,優(yōu)先級(jí)高的會(huì)先被通知
    int size = subscriptions.size();
    for (int i = 0; i <= size; i++) {
        if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
            subscriptions.add(i, newSubscription);
            break;
        }
    }

    //根據(jù)subscriber(訂閱者)來(lái)獲取它的所有訂閱事件
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        //把訂閱者、事件放進(jìn)typesBySubscriber這個(gè)Map中
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);

    //下面是對(duì)粘性事件的處理
    if (subscriberMethod.sticky) {
        //從EventBusBuilder可知亲配,eventInheritance默認(rèn)為true.
        if (eventInheritance) {
            // Existing sticky events of all subclasses of eventType have to be considered.
            // Note: Iterating over all events may be inefficient with lots of sticky events,
            // thus data structure should be changed to allow a more efficient lookup
            // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
            Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry<Class<?>, Object> entry : entries) {
                Class<?> candidateEventType = entry.getKey();
                if (eventType.isAssignableFrom(candidateEventType)) {
                    Object stickyEvent = entry.getValue();
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            //根據(jù)eventType尘应,從stickyEvents列表中獲取特定的事件
            Object stickyEvent = stickyEvents.get(eventType);
            //分發(fā)事件
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

到目前為止,注冊(cè)流程基本分析完畢吼虎,而關(guān)于最后的粘性事件的處理犬钢,這里暫時(shí)不說(shuō),下面會(huì)詳細(xì)進(jìn)行講述思灰$栌蹋可以看出,整個(gè)注冊(cè)流程非常地長(zhǎng)官辈,方法的調(diào)用棧很深箱舞,在各個(gè)方法中不斷跳轉(zhuǎn)遍坟,那么為了方便讀者理解,下面給出一個(gè)流程圖晴股,讀者可結(jié)合該流程圖以及上面的詳解來(lái)進(jìn)行理解愿伴。


注冊(cè)流程

注銷

與注冊(cè)相對(duì)應(yīng)的是注銷,當(dāng)訂閱者不再需要事件的時(shí)候电湘,我們要注銷這個(gè)訂閱者隔节,即調(diào)用以下代碼:

EventBus.getDefault().unregister(this);

那么我們來(lái)分析注銷流程是怎樣實(shí)現(xiàn)的,首先查看EventBus#unregister

unregister

public synchronized void unregister(Object subscriber) {
    //根據(jù)當(dāng)前的訂閱者來(lái)獲取它所訂閱的所有事件
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        //遍歷所有訂閱的事件
        for (Class<?> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        //從typesBySubscriber中移除該訂閱者
        typesBySubscriber.remove(subscriber);
    } else {
        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

上面調(diào)用了EventBus#unsubscribeByEventType,把訂閱者以及事件作為參數(shù)傳遞了進(jìn)去寂呛,那么應(yīng)該是解除兩者的聯(lián)系怎诫。

unsubscribeByEventType

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
    //根據(jù)事件類型從subscriptionsByEventType中獲取相應(yīng)的 subscriptions 集合
    List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    if (subscriptions != null) {
        int size = subscriptions.size();
        //遍歷所有的subscriptions,逐一移除
        for (int i = 0; i < size; i++) {
            Subscription subscription = subscriptions.get(i);
            if (subscription.subscriber == subscriber) {
                subscription.active = false;
                subscriptions.remove(i);
                i--;
                size--;
            }
        }
    }
}

可以看到贷痪,上面兩個(gè)方法的邏輯是非常清楚的幻妓,都是從typesBySubscriber或subscriptionsByEventType移除相應(yīng)與訂閱者有關(guān)的信息,注銷流程相對(duì)于注冊(cè)流程簡(jiǎn)單了很多劫拢,其實(shí)注冊(cè)流程主要邏輯集中于怎樣找到訂閱方法上肉津。

發(fā)送事件

接下來(lái),我們分析發(fā)送事件的流程舱沧,一般地妹沙,發(fā)送一個(gè)事件調(diào)用以下代碼:

EventBus.getDefault().post(new MessageEvent("Hello !....."));`

我們來(lái)看看EventBus#post方法。

post

public void post(Object event) {
    //1熟吏、 獲取一個(gè)postingState
    PostingThreadState postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;
    //將事件加入隊(duì)列中
    eventQueue.add(event);

    if (!postingState.isPosting) {
        //判斷當(dāng)前線程是否是主線程
        postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
        postingState.isPosting = true;
        if (postingState.canceled) {
            throw new EventBusException("Internal error. Abort state was not reset");
        }
        try {
            //只要隊(duì)列不為空距糖,就不斷從隊(duì)列中獲取事件進(jìn)行分發(fā)
            while (!eventQueue.isEmpty()) {
                postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

邏輯非常清晰,首先是獲取一個(gè)PostingThreadState牵寺,那么PostingThreadState是什么呢悍引?我們來(lái)看看它的類結(jié)構(gòu):

PostingThreadState

final static class PostingThreadState {
    final List<Object> eventQueue = new ArrayList<Object>();
    boolean isPosting;
    boolean isMainThread;
    Subscription subscription;
    Object event;
    boolean canceled;
}

可以看出,該P(yáng)ostingThreadState主要是封裝了當(dāng)前線程的信息缸剪,以及訂閱者吗铐、訂閱事件等。那么怎么得到這個(gè)PostingThreadState呢杏节?讓我們回到post()方法唬渗,看①號(hào)代碼,這里通過(guò)currentPostingThreadState.get()來(lái)獲取PostingThreadState奋渔。那么currentPostingThreadState又是什么呢镊逝?

private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
    @Override
    protected PostingThreadState initialValue() {
        return new PostingThreadState();
    }
};

原來(lái) currentPostingThreadState是一個(gè)ThreadLocal,而ThreadLocal是每個(gè)線程獨(dú)享的嫉鲸,其數(shù)據(jù)別的線程是不能訪問(wèn)的撑蒜,因此是線程安全的。我們?cè)俅位氐絇ost()方法,繼續(xù)往下走座菠,是一個(gè)while循環(huán)狸眼,這里不斷地從隊(duì)列中取出事件,并且分發(fā)出去浴滴,調(diào)用的是EventBus#postSingleEvent方法拓萌。

postSingleEvent

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    //該eventInheritance上面有提到,默認(rèn)為true升略,即EventBus會(huì)考慮事件的繼承樹(shù)
    //如果事件繼承自父類微王,那么父類也會(huì)作為事件被發(fā)送
    if (eventInheritance) {
        //查找該事件的所有父類
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
        int countTypes = eventTypes.size();
        //遍歷所有事件
        for (int h = 0; h < countTypes; h++) {
            Class<?> clazz = eventTypes.get(h);
            subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
        }
    } else {
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
    }
    //如果沒(méi)找到訂閱該事件的訂閱者
    if (!subscriptionFound) {
        if (logNoSubscriberMessages) {
            Log.d(TAG, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}

從上面的邏輯來(lái)看,對(duì)于一個(gè)事件品嚣,默認(rèn)地會(huì)搜索出它的父類炕倘,并且把父類也作為事件之一發(fā)送給訂閱者,接著調(diào)用了EventBus#postSingleEventForEventType翰撑,把事件罩旋、postingState、事件的類傳遞進(jìn)去眶诈,那么我們來(lái)看看這個(gè)方法瘸恼。

postSingleEventForEventType

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        //從subscriptionsByEventType獲取響應(yīng)的subscriptions
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        for (Subscription subscription : subscriptions) {
            postingState.event = event;
            postingState.subscription = subscription;
            boolean aborted = false;
            try {
                //發(fā)送事件
                postToSubscription(subscription, event, postingState.isMainThread);
                aborted = postingState.canceled;
            } 
            //...
        }
        return true;
    }
    return false;
}

接著,進(jìn)一步調(diào)用了EventBus#postToSubscription,可以發(fā)現(xiàn)册养,這里把訂閱列表作為參數(shù)傳遞了進(jìn)去,顯然压固,訂閱列表內(nèi)部保存了訂閱者以及訂閱方法球拦,那么可以猜測(cè),這里應(yīng)該是通過(guò)反射的方式來(lái)調(diào)用訂閱方法帐我。具體怎樣的話坎炼,我們看源碼。

postToSubscription

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
    switch (subscription.subscriberMethod.threadMode) {
        case POSTING:
            invokeSubscriber(subscription, event);
            break;
        case MAIN:
            if (isMainThread) {
                invokeSubscriber(subscription, event);
            } else {
                mainThreadPoster.enqueue(subscription, event);
            }
            break;
        case BACKGROUND:
            if (isMainThread) {
                backgroundPoster.enqueue(subscription, event);
            } else {
                invokeSubscriber(subscription, event);
            }
            break;
        case ASYNC:
            asyncPoster.enqueue(subscription, event);
            break;
        default:
            throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
    }
}

首先獲取threadMode拦键,即訂閱方法運(yùn)行的線程谣光,如果是POSTING,那么直接調(diào)用invokeSubscriber()方法即可芬为,如果是MAIN萄金,則要判斷當(dāng)前線程是否是MAIN線程,如果是也是直接調(diào)用invokeSubscriber()方法媚朦,否則會(huì)交給mainThreadPoster來(lái)處理氧敢,其他情況相類似。這里會(huì)用到三個(gè)Poster询张,由于粘性事件也會(huì)用到這三個(gè)Poster孙乖,因此我把它放到下面來(lái)專門講述义矛。而EventBus#invokeSubscriber的實(shí)現(xiàn)也很簡(jiǎn)單,主要實(shí)現(xiàn)了利用反射的方式來(lái)調(diào)用訂閱方法同辣,這樣就實(shí)現(xiàn)了事件發(fā)送給訂閱者工坊,訂閱者調(diào)用訂閱方法這一過(guò)程。如下所示:

invokeSubscriber

void invokeSubscriber(Subscription subscription, Object event) {
    try {
        subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
    } 
    //...
}

到目前為止恋拷,事件的發(fā)送流程也講解完畢资厉,為了方便理解,整個(gè)發(fā)送流程也給出相應(yīng)的流程圖:

發(fā)送流程.jpg

粘性事件的發(fā)送及接收分析

粘性事件與一般的事件不同梅掠,粘性事件是先發(fā)送出去酌住,然后讓后面注冊(cè)的訂閱者能夠收到該事件。粘性事件的發(fā)送是通過(guò)EventBus#postSticky()方法進(jìn)行發(fā)送的阎抒,我們來(lái)看它的源碼:

public void postSticky(Object event) {
    synchronized (stickyEvents) {
        stickyEvents.put(event.getClass(), event);
    }
    // Should be posted after it is putted, in case the subscriber wants to remove immediately
    post(event);
}

把該事件放進(jìn)了 stickyEvents這個(gè)map中酪我,接著調(diào)用了post()方法,那么流程和上面分析的一樣了且叁,只不過(guò)是找不到相應(yīng)的subscriber來(lái)處理這個(gè)事件罷了都哭。那么為什么當(dāng)注冊(cè)訂閱者的時(shí)候可以馬上接收到匹配的事件呢?還記得上面的EventBus#subscribe方法里面有一段是專門處理粘性事件的代碼嗎逞带?即:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //以上省略...
    //下面是對(duì)粘性事件的處理
    if (subscriberMethod.sticky) {
        //從EventBusBuilder可知欺矫,eventInheritance默認(rèn)為true.
        if (eventInheritance) {
            // Existing sticky events of all subclasses of eventType have to be considered.
            // Note: Iterating over all events may be inefficient with lots of sticky events,
            // thus data structure should be changed to allow a more efficient lookup
            // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
            //從列表中獲取所有粘性事件,由于粘性事件的性質(zhì)展氓,我們不知道它對(duì)應(yīng)哪些訂閱者穆趴,
            //因此,要把所有粘性事件取出來(lái)遇汞,逐一遍歷
            Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry<Class<?>, Object> entry : entries) {
                Class<?> candidateEventType = entry.getKey();
                //如果訂閱者訂閱的事件類型與當(dāng)前的粘性事件類型相同未妹,那么把該事件分發(fā)給這個(gè)訂閱者
                if (eventType.isAssignableFrom(candidateEventType)) {
                    Object stickyEvent = entry.getValue();
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            //根據(jù)eventType,從stickyEvents列表中獲取特定的事件
            Object stickyEvent = stickyEvents.get(eventType);
            //分發(fā)事件
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

上面的邏輯很清晰空入,EventBus并不知道當(dāng)前的訂閱者對(duì)應(yīng)了哪個(gè)粘性事件络它,因此需要全部遍歷一次,找到匹配的粘性事件后歪赢,會(huì)調(diào)用EventBus#checkPostStickyEventToSubscription方法:

private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
    if (stickyEvent != null) {
        // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
        // --> Strange corner case, which we don't take care of here.
        postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
    }
}

接著化戳,又回到了postToSubscription方法了,無(wú)論對(duì)于普通事件或者粘性事件埋凯,都會(huì)根據(jù)threadMode來(lái)選擇對(duì)應(yīng)的線程來(lái)執(zhí)行訂閱方法点楼,而切換線程的關(guān)鍵所在就是mainThreadPoster、backgroundPoster和asyncPoster這三個(gè)Poster白对。

HandlerPoster

我們首先看mainThreadPoster盟步,它的類型是HandlerPoster繼承自Handler:

final class HandlerPoster extends Handler {

    //PendingPostQueue隊(duì)列,待發(fā)送的post隊(duì)列
    private final PendingPostQueue queue;
    //規(guī)定最大的運(yùn)行時(shí)間躏结,因?yàn)檫\(yùn)行在主線程却盘,不能阻塞主線程
    private final int maxMillisInsideHandleMessage;
    private final EventBus eventBus;
    private boolean handlerActive;
    //省略...
}

可以看到,該handler內(nèi)部有一個(gè)PendingPostQueue,這是一個(gè)隊(duì)列黄橘,保存了PendingPost兆览,即待發(fā)送的post,該P(yáng)endingPost封裝了event和subscription塞关,方便在線程中進(jìn)行信息的交互抬探。在postToSubscription方法中,當(dāng)前線程如果不是主線程的時(shí)候帆赢,會(huì)調(diào)用HandlerPoster#enqueue方法:

void enqueue(Subscription subscription, Object event) {
    //將subscription和event打包成一個(gè)PendingPost
    PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
    synchronized (this) {
        //入隊(duì)列
        queue.enqueue(pendingPost);
        if (!handlerActive) {
            handlerActive = true;
            //發(fā)送消息小压,在主線程運(yùn)行
            if (!sendMessage(obtainMessage())) {
                throw new EventBusException("Could not send handler message");
            }
        }
    }
}

首先會(huì)從PendingPostPool中獲取一個(gè)可用的PendingPost,接著把該P(yáng)endingPost放進(jìn)PendingPostQueue椰于,發(fā)送消息怠益,那么由于該HandlerPoster在初始化的時(shí)候獲取了UI線程的Looper,所以它的handleMessage()方法運(yùn)行在UI線程:

@Override
public void handleMessage(Message msg) {
    boolean rescheduled = false;
    try {
        long started = SystemClock.uptimeMillis();
        //不斷從隊(duì)列中取出pendingPost
        while (true) {
            //省略...
            eventBus.invokeSubscriber(pendingPost);        
            //..
        }
    } finally {
        handlerActive = rescheduled;
    }
}

里面調(diào)用到了EventBus#invokeSubscriber方法瘾婿,在這個(gè)方法里面蜻牢,將PendingPost解包,進(jìn)行正常的事件分發(fā)偏陪,這上面都說(shuō)過(guò)了抢呆,就不展開(kāi)說(shuō)了。

BackgroundPoster

BackgroundPoster繼承自Runnable笛谦,與HandlerPoster相似的抱虐,它內(nèi)部都有PendingPostQueue這個(gè)隊(duì)列,當(dāng)調(diào)用到它的enqueue的時(shí)候饥脑,會(huì)將subscription和event打包成PendingPost:

public void enqueue(Subscription subscription, Object event) {
    PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
    synchronized (this) {
        queue.enqueue(pendingPost);
        //如果后臺(tái)線程還未運(yùn)行梯码,則先運(yùn)行
        if (!executorRunning) {
            executorRunning = true;
            //會(huì)調(diào)用run()方法
            eventBus.getExecutorService().execute(this);
        }
    }
}

該方法通過(guò)Executor來(lái)運(yùn)行run()方法,run()方法內(nèi)部也是調(diào)用到了EventBus#invokeSubscriber方法好啰。

AsyncPoster

與BackgroundPoster類似,它也是一個(gè)Runnable儿奶,實(shí)現(xiàn)原理與BackgroundPoster大致相同框往,但有一個(gè)不同之處,就是它內(nèi)部不用判斷之前是否已經(jīng)有一條線程已經(jīng)在運(yùn)行了闯捎,它每次post事件都會(huì)使用新的一條線程椰弊。

再談?dòng)^察者模式

整個(gè)EventBus是基于觀察者模式而構(gòu)建的,而上面的調(diào)用觀察者的方法則是觀察者模式的核心所在瓤鼻。

觀察者模式:定義了對(duì)象之間的一對(duì)多依賴秉版,當(dāng)一個(gè)對(duì)象改變狀態(tài)時(shí),它的所有依賴者都會(huì)收到通知并自動(dòng)更新茬祷。

從整個(gè)EventBus可以看出清焕,事件是被觀察者,訂閱者類是觀察者,當(dāng)事件出現(xiàn)或者發(fā)送變更的時(shí)候秸妥,會(huì)通過(guò)EventBus通知觀察者滚停,使得觀察者的訂閱方法能夠被自動(dòng)調(diào)用。當(dāng)然了粥惧,這與一般的觀察者模式有所不同键畴。回想我們所用過(guò)的觀察者模式突雪,我們會(huì)讓事件實(shí)現(xiàn)一個(gè)接口或者直接繼承自Java內(nèi)置的Observerable類起惕,同時(shí)在事件內(nèi)部還持有一個(gè)列表,保存所有已注冊(cè)的觀察者咏删,而事件類還有一個(gè)方法用于通知觀察者的惹想。那么從單一職責(zé)原則的角度來(lái)說(shuō),這個(gè)事件類所做的事情太多啦饵婆!既要記住有哪些觀察者勺馆,又要等到時(shí)機(jī)成熟的時(shí)候通知觀察者,又或者有別的自身的方法侨核。這樣的話草穆,一兩件事件類還好,但如果對(duì)于每一個(gè)事件類搓译,每一個(gè)新的不同的需求悲柱,都要實(shí)現(xiàn)相同的操作的話,這是非常繁瑣而且低效率的些己。因此豌鸡,EventBus就充當(dāng)了中介的角色,把事件的很多責(zé)任抽離出來(lái)段标,使得事件自身不需要實(shí)現(xiàn)任何東西涯冠,別的都交給EventBus來(lái)操作就可以了。

好了逼庞,本文到此為止已經(jīng)對(duì)EventBus進(jìn)行了一次詳細(xì)的講解蛇更,由于本文很長(zhǎng),建議讀者可以選擇難懂的部分對(duì)照源碼反復(fù)思考以便能深刻理解赛糟。最后派任,為堅(jiān)持讀完本文的你點(diǎn)贊,謝謝你們的閱讀璧南!

更多閱讀
EventBus 3.0初探: 入門使用及其使用 完全解析
學(xué)習(xí)掌逛、探究Java設(shè)計(jì)模式——觀察者模式

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市司倚,隨后出現(xiàn)的幾起案子豆混,更是在濱河造成了極大的恐慌篓像,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,427評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件崖叫,死亡現(xiàn)場(chǎng)離奇詭異遗淳,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)心傀,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門屈暗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人脂男,你說(shuō)我怎么就攤上這事养叛。” “怎么了宰翅?”我有些...
    開(kāi)封第一講書人閱讀 165,747評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵弃甥,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我汁讼,道長(zhǎng)淆攻,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書人閱讀 58,939評(píng)論 1 295
  • 正文 為了忘掉前任嘿架,我火速辦了婚禮瓶珊,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘耸彪。我一直安慰自己伞芹,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布蝉娜。 她就那樣靜靜地躺著唱较,像睡著了一般。 火紅的嫁衣襯著肌膚如雪召川。 梳的紋絲不亂的頭發(fā)上南缓,一...
    開(kāi)封第一講書人閱讀 51,737評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音荧呐,去河邊找鬼汉形。 笑死,一個(gè)胖子當(dāng)著我的面吹牛坛增,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播薄腻,決...
    沈念sama閱讀 40,448評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼收捣,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了庵楷?” 一聲冷哼從身側(cè)響起罢艾,我...
    開(kāi)封第一講書人閱讀 39,352評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤楣颠,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后咐蚯,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體童漩,經(jīng)...
    沈念sama閱讀 45,834評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評(píng)論 3 338
  • 正文 我和宋清朗相戀三年春锋,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了矫膨。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,133評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡期奔,死狀恐怖侧馅,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情呐萌,我是刑警寧澤馁痴,帶...
    沈念sama閱讀 35,815評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站肺孤,受9級(jí)特大地震影響罗晕,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜赠堵,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評(píng)論 3 331
  • 文/蒙蒙 一小渊、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧顾腊,春花似錦粤铭、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 32,022評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至吗垮,卻和暖如春垛吗,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背烁登。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 33,147評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工怯屉, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人饵沧。 一個(gè)月前我還...
    沈念sama閱讀 48,398評(píng)論 3 373
  • 正文 我出身青樓锨络,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親狼牺。 傳聞我的和親對(duì)象是個(gè)殘疾皇子羡儿,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容