Swift Combine: TypeEraser, things you might have never known of
What is type eraser? The problem is that you might have used it without knowing it correctly. Nothing can be more dangerous than using the code that you don’t have any idea of how it works. If you had never known it, rest assured, I will explain it now in the simplest language possible.
TypeEraser
When using Combine Framework, you will come across TypeEraser
concept. This actually has nothing to do with Combine Framework. This is rather a feature of the language.
But TypeEraser by its terms seems somewhat strange because it doesn’t actually remove the type. It actually hides the type behind some other type.
Specific Publisher
let publisher = PassthroughSubject<Int, Never>()
Let’s create PassthroughSubject which handles Integer and is never going to fail.
In some cases, you want to hide the details about the type of the publisher that you have used.
So, you don’t want the client or someone else who is using the publisher to know that you are using PassthroughSubject
through subject publisher. You want to keep it private.
What can you do now for it?
eraseToAnyPublisher()
let publisher: AnyPublisher<Int, Never> = PassthroughSubject<Int, Never>().eraseToAnyPublisher()
So what you do in his case is you are actually calling a function which is called eraseToAnyPublisher()
. It’s not going to erase anything. It’s simply going to put your PassthroughSubject behind another publisher. This is called AnyPublisher
.
Actually, if you start typing this, you will see that it is going to return use to AnyPublisher instead of a PassthroughSubject Publisher.
Side Effects??
let publisher: AnyPublisher<Int, Never> = PassthroughSubject<Int, Never>().eraseToAnyPublisher()
publisher.send() // not working.
If you apply this, all the functionalities related with PassthroughSubject are gone because you have hidden the type behind AnyPublisher.
Because your code now will not know the inner details and the title of the publisher that your code is using. Your code won’t know exactly what kind of a publisher that you have used.
Conclusion
You can hide your publisher type by using eraseToAnyPublisher()
.
Then, your publisher becomes AnyPublisher
.
The whole idea of the type eraser is to simply put your concrete type behind some other type(AnyPublisher).