Charles
Charles

Reputation: 25

Using immutable Map structure as an Observable

I am trying to implement a synchronization mechanism with observable and Map structure from Immutable.js.

It’s not working because Map cannot be an observable or maybe because I do it the wrong way.

I have tried to look into the Rx doc, use just, return, from, of … nothing seems to fit for a Map.

What I need is to wait to have my Map completed (with the value I get from a http.GET) before doing what I put in the subscribe callback.


import {List, Map} from 'immutable';
import {Observable} from 'rxjs/Observable';
...

processNewTopology(topology: List<Endpoint>): Observable<Map<string, any>> {

    let ip: string = JSON.stringify(topology.get(0).ueIpAddress);

    //this function is just a http GET that returns an osbervable string (imsi)
    this.apiService.getImsiFromAAA(ip).subscribe(
            imsi  => myMap = this.reduceEndpointsToMap( imsi, topology),
            error =>  this.errorMessage = <any>error
          );

    return myMap; // I need in some way to convert my map into an obervable

  }


private reduceEndpointsToMap(imsi: string, topology: List<Endpoint>): Map<string, any> {
    // this function take the imsi and a list point and build the map and return it
    // the imsi is provided by http.GET
}

So in another class I call processNewTopology to get the Map. I need to have my map before doing the display actions

this.topologyService.processNewTopology(endpoints).subscribe(
          myMap => {
            // here I want to access the content of myMap to display the new topo
          }
          ...
        );

Upvotes: 1

Views: 513

Answers (1)

Shane
Shane

Reputation: 3199

You're using the Obserable as an es6 Promise. Best solution would be to wrap the http request from the api service into a Promise. You can easily resolve the result when the http request(s) have finished.

Service:

class TopologyService {

    private apiService: any;

    ...

    public processNewTopology(topology: List<Endpoint>): Promise<Map<string, any>> {
        let ip = JSON.stringify(topology.get(0).ueIpAddress);

        return new Promise((resolve, reject) => {
            this.apiService.getImsiFromAAA(ip).subscribe(
                response => resolve(this.reduceEndpointsToMap(response, topology)),
                error => reject(error)
            );
        });
    }

    private reduceEndpointsToMap(imsi: string, topology: List<Endpoint>): Map<string, any> {
        ...
    }

    ...
}

usage:

topologyService.processNewTopology(endpoints)
    .then(value => {
        // do something
    })
    .catch(err => {
        // error occured
    });

Upvotes: 1

Related Questions