Difference between Observable.defer and Observable.create in java rx

前端 未结 1 462
我寻月下人不归
我寻月下人不归 2021-02-11 16:41

Can someone explain me the difference between defer and create methods in Observable? I failed to understand when I should use defer

相关标签:
1条回答
  • 2021-02-11 17:15

    So the distinction seems to be: defer is good when you have something that creates/returns an observable already, but you don’t want it to that process to happen until subscription.

    create is good when you need to manually wrap an async process and create an observable. That creation is also deferred until subscription.

    To put it another way:

    defer is an operator that enables deferred composition of observable sequences.

    create is a custom implementation of observable sequence (where creation is deferred until subscription).

    So if you have a situation where you might use just to create an Observable from some results/value or you have a network API layer that returns an Observable of the request, but you don't want that request to kick off until subscription. defer would be good for those scenarios.

    If you have a network API layer that doesn't return an Observable for a request, but which you need an Observable interface to, you might use create. That Observable sequence still wouldn't be created until subscription though. If you wanted that network call to kick off regardless of subscription, then you would use a different mechanism, like a Subject, potentially that replays.

    0 讨论(0)
提交回复
热议问题