Rxswift What difference between Observable.of and

2019-05-24 02:00发布

I'm a newbie in rxSwift. I found some difference when create Observable by Observable.of and Observable<String>.create

    Observable<String>.create { observer in

    observer.onNext("1")

    observer.onNext("2")

    return Disposables.create()
    }.take(3).toArray().subscribe(onNext: { (item) in
        print(item)
    }).disposed(by: disposeBag)

Not emitted util received at least 3 event. In this way observer never emitted. But with:

    Observable.of("1", "2")
    // 2
    .take(3).toArray()
    .subscribe(onNext: {
        print($0) })
    .disposed(by: disposeBag)

But when i create by this way. Observer always emitted even if i just have 2 elements. I don't known what difference.

标签: rx-swift
1条回答
你好瞎i
2楼-- · 2019-05-24 02:36

The main difference is that of sends a completed event as well. You can check the example below, the second "completed" will not be called.

You have to write observer.onCompleted() after observer.onNext("2") it order to have the same logic.

Observable.of("1", "2").subscribe(onCompleted: {
    print("completed")
})

Observable<String>.create { observer in
        observer.onNext("1")
        observer.onNext("2")
        return Disposables.create()
    }
    .subscribe(onCompleted: {
        print("completed")
    })
查看更多
登录 后发表回答