实现简单的 RxKotlin (下)

其他的一些操作符...

doOnNext ( doOnError doOnCompleted)

//Observable.kt
fun doOnNext(action: (t: T) -> Unit): Observable {
    return create(OnSubscribeDoOnNext(this, action))
}

//OnSubscribeDoOnNext.kt
class OnSubscribeDoOnNext(private var source: Observable, private var action: (T) -> Unit) : Observable.OnSubscribe {

    override fun call(subscriber: Subscriber) {
        source.subscribe(object : Subscriber(){
            override fun onCompleted() {
                subscriber.onCompleted()
            }

            override fun onError(t: Throwable) {
                subscriber.onError(t)
            }

            override fun onNext(t: T) {
                action(t)
                subscriber.onNext(t)
            }
        })
    }
}

compose

fun  compose(transformer: (t : Observable) -> Observable): Observable {
    return transformer(this)
}

from(array: Array)

//Observable.kt
companion object {

    fun  from(array: Array): Observable {
        return create(OnSubscribeFromArray(array))
    }

}

//OnSubscribeFromArray
class OnSubscribeFromArray(private var array : Array) : Observable.OnSubscribe {

    override fun call(subscriber: Subscriber) {
        try {
            for (t in array) {
                if (!subscriber.isUnsubscribed())
                    subscriber.onNext(t)
            }
        }catch (e: Exception) {
            subscriber.onError(e)
        }
        subscriber.onCompleted()
    }

}

merge

//Observable.kt
companion object {

    fun  merge(source : Observable>): Observable {
        return source.lift(OperatorMerge())
    }

    fun  merge(array: Array>): Observable {
        return merge(from(array))
    }
}

//OperatorMerge.kt
class OperatorMerge : Observable.Operator> {

    override fun call(subscriber: Subscriber): Subscriber> {
        return MergeSubscriber(subscriber)
    }

    private class MergeSubscriber(private var actual : Subscriber) : Subscriber>() {

        override fun onCompleted() {
        }

        override fun onError(t: Throwable) {
        }

        override fun onNext(t: Observable) {
            t.subscribe(actual)
        }

    }
}

flatMap

fun  flatMap(func: (t: T) -> Observable): Observable{
    return merge(map(func))
}

你可能感兴趣的:(实现简单的 RxKotlin (下))