fromEventPattern
Creates an Observable from an arbitrary API for registering event handlers.
Parameters
Returns
Observable<T | T[]>
: Observable which, when an event happens, emits first parameter
passed to registered event handler. Alternatively it emits whatever project function returns
at that moment.
Description
When that method for adding event handler was something fromEvent
was not prepared for.
fromEventPattern
allows you to convert into an Observable any API that supports registering handler functions
for events. It is similar to fromEvent
, but far
more flexible. In fact, all use cases of fromEvent
could be easily handled by
fromEventPattern
(although in slightly more verbose way).
This operator accepts as a first argument an addHandler
function, which will be injected with
handler parameter. That handler is actually an event handler function that you now can pass
to API expecting it. addHandler
will be called whenever Observable
returned by the operator is subscribed, so registering handler in API will not
necessarily happen when fromEventPattern
is called.
After registration, every time an event that we listen to happens,
Observable returned by fromEventPattern
will emit value that event handler
function was called with. Note that if event handler was called with more
then one argument, second and following arguments will not appear in the Observable.
If API you are using allows to unregister event handlers as well, you can pass to fromEventPattern
another function - removeHandler
- as a second parameter. It will be injected
with the same handler function as before, which now you can use to unregister
it from the API. removeHandler
will be called when consumer of resulting Observable
unsubscribes from it.
In some APIs unregistering is actually handled differently. Method registering an event handler
returns some kind of token, which is later used to identify which function should
be unregistered or it itself has method that unregisters event handler.
If that is the case with your API, make sure token returned
by registering method is returned by addHandler
. Then it will be passed
as a second argument to removeHandler
, where you will be able to use it.
If you need access to all event handler parameters (not only the first one),
or you need to transform them in any way, you can call fromEventPattern
with optional
third parameter - project function which will accept all arguments passed to
event handler when it is called. Whatever is returned from project function will appear on
resulting stream instead of usual event handlers first argument. This means
that default project can be thought of as function that takes its first parameter
and ignores the rest.