-
Notifications
You must be signed in to change notification settings - Fork 20
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to avoid calling map function multiple times? #31
Comments
@zsoerenm What you are looking for is the fooS = RecentSubject(String)
# Added the `|> share()` operator
mappedAndSharedFooS = fooS |> map(String, x -> begin println("Called"); x end) |> share()
subscribe!(mappedAndSharedFooS, logger())
subscribe!(mappedAndSharedFooS, logger())
next!(fooS, "Test") Output Called # appears only once
[LogActor] Data: Test
[LogActor] Data: Test The Under the hood, the Without # I use the `from` instead of a `Subject`, which sends all data at once and completes immediately
fooS = from([ "Hello", "world!" ])
mappedFooS = fooS |> map(String, x -> begin println("Called"); x end)
subscribe!(mappedFooS, logger())
subscribe!(mappedFooS, logger())
# Called
# [LogActor] Data: Hello
# Called
# [LogActor] Data: world!
# [LogActor] Completed
# Called
# [LogActor] Data: Hello
# Called
# [LogActor] Data: world!
# [LogActor] Completed With fooS = from([ "Hello", "world!" ])
mappedAndSharedFooS = fooS |> map(String, x -> begin println("Called"); x end) |> share()
subscribe!(mappedAndSharedFooS, logger())
subscribe!(mappedAndSharedFooS, logger())
# Called
# [LogActor] Data: Hello
# Called
# [LogActor] Data: world!
# [LogActor] Completed
# [LogActor] Completed The second actor will not receive any shared values, because the first actor exhausted the observable till its completion stage. |
Thank you for clarifying! |
Here is a MWE:
Output
I intentionally subscribed to
mappedFooS
twice. Is doesn't need to be a subscription, it could also be any other map function with a subscription. The problem is that the map function insidemappedFooS
get called twice even though it only needs to be called once in theory. If the map function does some heavy calculation things can become quite slow.Is there a solution to this?
The text was updated successfully, but these errors were encountered: