Home > Net >  How to execute an observable conditionally? (Depending on a variable state in class level)
How to execute an observable conditionally? (Depending on a variable state in class level)

Time:07-01

Can someone tell me if there is a clean way to return an observable conditionally, depending on a pre-defined condition?

Let us consider the following scenario,

isEditing = false;  // <---- This is a variable defined in the class level

return this.usersService.fetchInitialCreateData()  // <---- Observable 1
  .subscribe(
    (response) => {
      this.userBranches = response[0];
      this.userPermissionGroups = response[1];
      this.userRoles = response[2];

      return this.usersService.fetchInitialEditData(this.userId) // <---- Observable 2
        .subscribe(
          (response) => {
            this.isLoading = false;

            this.createUserForm.setValue({
              'primaryData': {
                'name': response.name,
                'username': response.username,
                'email': response.email,
                'contactNumber': response.contactNumber,
                'branch': response.branchCode,
                'role': response.role
              },
              'permissions': [],
              'userPassword': null,
              'userStatus': response.isActive ? 'active' : 'inactive'     
            });
          },
          (error) => {
            this.isLoading = false;
          }
        )
    }
  );

In the above example you can see two observables (marked as Observable 1 and Observable 2) and a variable in the class level (marked as This is a variable defined in the class level)

Following are the conditions of the output I am trying to achieve,

  1. Observable 2 should be executed only upon receiving a success response from the Observable 1
  2. From the two observables, the final return value should be Observable 1, if isEditing = false, the final return value should be Observable 2 if isEditing = true

Whether the Observable 1 is return or the Observable 2 is returned as the final observable should be dependent upon the isEditing property.

I tried hard and hard, but I could not achieve this. Could someone please help me?

Thank You!

CodePudding user response:

My brief suggestion:

obervable1.pipe(
  switchMap(obs1-result => forkJoin(of(obs1-result), observable2)),
  map([obs1-result, obs2-result] => isEditing ? obs1-result : obs2-result
).subscribe();

Please have a look at the example here: working example

  • Related