问题
DRY (Don't Repeat Yourself)
Suppose I have this code used a lot in my app:
observable$.pipe(
tap(value => console.log(value)),
map(value => value * 5),
... more repeated stuff
)
Suppose that the value 5 is different in some parts of the code but everything else is identical. Can I somehow functionalise / do something to this to make it reusable to avoid copy paste issues?
Could I do something like this?
observable$.pipe(
getReusedOperators(7), // this would pipe to all above operators using 7 instead of 5
tap((value) => console.log('im not reused and my value is', value)),
....
)
What is the best approach here? Sorry, my question not great but hopefully you get the idea.
回答1:
The thing to remember with pipeable operators is that they are just functions that take an observable and return an observable, so you can easily create reusable combinations of operators like this:
function getReusedOperators(factor) {
return source => source.pipe(
tap(value => console.log(value)),
map(value => value * factor),
);
}
And for situations in which your reusable combination is not parameterized, you can just compose using the static pipe
function. See my Combining Operators article for some examples.
回答2:
If you want something reusable that you can add to a pipe, you can write a method that returns an OperatorFunction (defined in rxjs). The pipe operator takes one or more OperatorFunctions as parameters.
Here's an example of one of these that I'm using in my application:
/*
* Returns an "OperatorFunction", suitable for passing to rx.pipe(),
* that maps a Role[] to a sorted FormRole[] (sorted by role name)
*/
public rolesToSortedFormRolesMapper(): OperatorFunction<Role[], FormRole[]> {
return map((roles: Role[]) => roles.map((role) =>
new FormRole(role.role, role.name, false)
).sort((lhs, rhs) => (lhs.name.localeCompare(rhs.name)))
);
}
This OperatorFunction maps an array of one type to an array of another type, and then sorts the result.
It can be used with, for example,
someObservable.pipe(rolesToSortedFormRolesMapper())
Of course, you could put other operators into the pipe as well.
来源:https://stackoverflow.com/questions/51795469/how-to-keep-rxjs-dry