0

I'm pretty new to functional reactive programming and I have a question on how to design a service (a class within my web application frontend) that creates a viewmodel of a chart.

For now it is like this:

To use this service, I pass in some input streams as parameters and I get back an output stream.

One of those input streams streams will emit an event if the chart should load new data, another input stream will emit an event if the selected time range changes and so on. The response stream emits viewmodels.

So the call looks kind of this:


const viewModel$ = lineChart.createChart(timeRange$, refresh$)

viewModel$.subscribe((viewModel) => renderMyChart(viewModel))

Now I don't want this service to create side effects. Right now the service is making a http request to the backend, but I want to extract this call and I wander how this is done usually in functional reactive programming.

My idea so far is, that I would also return a stream that emits an event whenever the service decides to ask for new data. And I would pass in also an input stream that would emit those data (the responses from the http request):


const [requestData$, viewModel$] = lineChart.createChart(timeRange$, refresh$, data$)

requestData$.subscribe((request) => {
    someService.fetchData(request).subscribe((response) => data$.next(response)
})

viewModel$.subscribe((viewModel) => renderMyChart(viewModel))

For me it seems a bit weird to pass in a data stream and to have returned two streams and to copy the responses to the data stream. How is this done usually? Do there exist common patterns for that?

stofl
  • 2,950
  • 6
  • 35
  • 48
  • 1
    just curious, any reason for the `$` appearing everywhere? – Mulan Nov 25 '21 at 18:34
  • 1
    The `$` suffix is just a [convention](https://stackoverflow.com/a/37928549/1858357) indicating that the variable is an observable. – BizzyBob Nov 25 '21 at 18:37
  • 1
    Subscribing to events is already side-effecty, so the code in question is already impure. Why bother? – Mark Seemann Nov 25 '21 at 21:35
  • @MarkSeemann Yes, I agree. Adding a subscription is a side-effect. In my case the input streams are of type `Subject`. Those are hot observables in RxJS which means that they fire the event regardless of the fact if and how many subscribers are listening to it. So although subscribing is technically still a side effect since it changes the state of the observable, it does effectively not change the outside world. So I would ignore that fact. – stofl Dec 01 '21 at 11:25

0 Answers0