It's a good practice to create my own Observable extended classes? i want to implement my own Single and Completable classes for the sake of know the amount or absence of data than and observable can return and i want it as a class because i use reclect-metadata
and i use design:returntype
in my decorators so i need a classes not an alias (because using alias the type returned will be always Object and not the original class constructor).
The idea is: for Single observables use the single operator and for Completable observables use the ignoreElements operators but without a class in Typescript for Singles i don't know the amount of data by only reading in the code Observable, that observable can return one or many or none and i want a Single for particular cases, this is what i want:
// some methods in some class
loginUser(userName: string, password: string): Single<User>
saveUser(user: User): Completable
For my this is more readable (because i use RxJava 2 in my Android projects) and with that i know that expect or not, without that i need to do:
loginUser(userName: string, password: string): Observable<User> // if i chain this with other observables i don't know how much users this will return
saveUser(user: User): Observable<void> // simply ugly
That is not good for my eyes you know? so i want to create that classes for a better read of my code and better implementation.
There are very good reasons why you'd want to be more specific about the actual behavior of the Observable. Unfortunately, there is no built-in mechanism in RxJS to specify this.
Extending the Observable will probably be very hard if you're using operators, because they are glued together using internally created Subjects.
Instead of using classes and the reflect-metadata
API at runtime, would it be sufficient to use types (interfaces) instead? These can help to document the behavior of the Observable to other developers and also be used for compile-time checks (e.g. a function that only accepts the type Single
).
There is a project that can serve as a starting point how this can be achieved: https://github.com/cartant/rxjs-traits
It implements type checking for a few operators and calculates the final type of the Observable based on these operators. Unfortunately it does not seem to be continued at the moment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With