Behavior Subject unsubscribe refactor - behaviorsubject

This can't be the only way to unsub Behavior Subjects :
maxSub;
fromSub;
toSub;
pageNumberSub;
originalMaxSub;
selectionSub;
selectionOfInterestSub;
constructor(private store: StoreService) {}
ngAfterContentChecked(){
this.maxSub = this.store.max$.subscribe((max) => {
if(max !== null && max !== undefined){
this.max = max;
this.maxPages = Math.floor(this.max / Variables.to);
this.pages = Array.from(Array(this.maxPages), (x, i) => i + 1);
}
}, (error) => console.log(error), () => {});
this.fromSub = this.store.from$.subscribe((from) => {
if(from !== null && from !== undefined) {this.from = from; this.split = this.to - (this.from - 1)}
}, (error) => console.log(error), () => {});
this.toSub = this.store.to$.subscribe((to) => {
if(to !== null && to !== undefined) {this.to = to; this.split = this.to - (this.from - 1)}
}, (error) => console.log(error), () => {});
this.pageNumberSub = this.store.pageNumber$.subscribe((pageNumber) => {
if(pageNumber !== null && pageNumber !== undefined) {this.page = pageNumber;}
}, (error) => console.log(error), () => {});
this.originalMaxSub = this.store.originalMax$.subscribe((originalMax) => {
if(originalMax !== null && originalMax !== undefined) {this.originalMax = originalMax;}
}, (error) => console.log(error), () => {});
this.selectionSub = this.store.selection$.subscribe((selection) => {
if(selection !== null && selection !== undefined) this.selectedAmount = selection.length;
}, (error) => console.log(error), () => {});
this.selectionOfInterestSub = this.store.selectionOfInterest$.subscribe((selectionOfInterest) => {
if(selectionOfInterest !== null && selectionOfInterest !== undefined) this.selectionOfInterest = selectionOfInterest;
}, (error) => console.log(error), () => {});
}
ngOnDestroy(){
this.maxSub.unsubscribe();
this.fromSub.unsubscribe();
this.toSub.unsubscribe();
this.pageNumberSub.unsubscribe();
this.originalMaxSub.unsubscribe();
this.selectionSub.unsubscribe();
this.selectionOfInterestSub.unsubscribe();
}
in regular old Observables you can just :
alive = true;
constructor(private store: StoreService) {}
ngAfterContentChecked(){
this.store.thing.subscribe().takeWhile(this.alive)...
}
ngOnDestroy(){
this.alive = false;
}
which is much simpler.
Isn't there a way to do the same with Behavior Subjects?
Another thing : am I missing a fundamental property of Behavior Subjects that they only subscribe once within an class no matter how many times the subscribe is called and that's why there's no such thing as takeWhile() on Behavior Subjects?

1 - Actually what you call it a simpler way does not unsubscribe at all it just stop reading what comes from the observable. So either use unsubscribe or complete.
2 - Since you are unsubscribing at the same time and you clearluy don't use the Subject for anything else, then it's fine to use the same Subject variable for all your subs and then you can unsubscribe with oneline of code and you don't need to initialize all these Subject instances.

Related

In React-native i'm using 'sharingan-rn-modal-dropdown'; Dropdown in form for add and edit data but selected values not getting reflected in dropdown

what exactly is happening is when i select the delivery service onChangeService i'm setting the next dropdown i.e. carrier's list.Also i'm setting the selected carrier as per the service.But all the time value is getting set correctly in {this.state.selectedCarrierName} but still i can show its label only.lists contain label an value pair
async onChangeService(value) {
//{ ...this.props.deliveryOptionsValue, selected: value.value === value }
this.setState({ newCarrierList: [], selectedCarrierName: '', selectedCararierName: '' });
const priceDeliveryService = this.props.orderDetailsDTO.priceDeliveryServiceDTOs;
console.log("carriers", JSON.stringify(this.props.carriers));
var newList = [];
var carrier = '';
await priceDeliveryService.forEach(m => {
console.log("compare", m.serviceId === value.id);
if (m.serviceId === value.id) {
console.log("carrier", JSON.stringify(this.props.carriers));
let l = this.props.orderDetailsDTO.carriers.filter(n => n.id === m.carrierId);
console.log("l", l);
if (l !== undefined) {
// / orderList: [...this.state.orderList, ...content]
// this.setState({ newCarrierList: [...this.state.newCarrierList, ...l[0]] });
newList.push(l[0]);
console.log("defa", newList);
if (m.defaultCarrierService) {
this.setState({ selectedCarrier: l[0], selectedCarrierName: l[0].name });
carrier = l[0].name;
} else {
this.setState({ selectedCarrier: newList[0], selectedCarrierName: newList[0].name });
carrier = newList[0].name;
}
}
}
});
const list = newList.map(item => ({
label: item.name,
value: item
}));
this.setState({ newCarrierListValue: list, newCarrierList: newList })
console.log("newCarrierListValue", list);
console.log("newCarrierList", newList);
// console.log("carrier service", p.carrierName, value.id);
const carrierServices = this.props.orderDetailsDTO.carrierServiceDTO;
console.log(carrierServices.length);
const pi = await this.setCarrierService(carrierServices, value, carrier);
// let pi;
// for (let i = 0; i < carrierServices.length; i++) {
// console.log("if", carrierServices[i].cdlServiceId == value.id, carrierServices[i].carrierName === carrier)
// if (carrierServices[i].cdlServiceId == value.id && carrierServices[i].carrierName === carrier) {
// console.log("mathced data", carrierServices[i]);
// pi = carrierServices[i];
// console.log(pi);
// break;
// }
// }
this.setState({ carrierService: pi.serviceName, carrierServices: carrierServices });
console.log(pi.serviceName);
}
<Dropdown required
label="Select delivery option"
data={this.props.deliveryOptionsValue}
// enableSearch
defaultValue={1}
value={this.state.selectedDeliveryOptionName}
onChange={(value) => {
console.log(" change value", value);
this.setState({ selectedDeliveryOptionName: value.name, selectedDeliveryOption: value, deliveryOptionError: false, });
this.onChangeService(value);
}} />
<Dropdown
required
label="Select a carrier"
data={this.state.newCarrierListValue}
// selectedValue={this.state.selectedCarrierName}
value={this.state.selectedCarrierName}
onChange={value => {
// console.log("value", value);
this.setState({ selectedCarrierName: value.name, selectedCarrier: value });
this.onChangeCarrier(value, this.state.selectedDeliveryOption);
}} />

How do I resolve a callback error with 'callback' is an instance of Object)?

TypeError: callback is not a function. (In 'callback(data)',
'callback' is an instance of Object)
The code here works just fine when I write it like this:
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
// { categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
When i uncomment that other line, it breaks and gives me this error.
const onSelectFilterDone = (filter) => {
setFilter(filter);
setFilterModalVisible(false);
unsubscribe.current = listingsAPI.subscribeListings(
{ categoryId: category.id },
{ categoryId2: category2.id },
favorites,
onListingsUpdate,
);
};
Here is the relevant snippet from listingsAPI (below) if it helps but this code works fine when there is only one object. Is there a specific way to make this work with two objects like above?
if (categoryId) {
return (
listingsRef
.where('categoryID', '==', categoryId)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}
if (categoryId2) {
return (
listingsRef
.where('categoryID2', '==', categoryId2)
.where('isApproved', '==', isApproved)
.onSnapshot((querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
const listing = doc.data();
if (favorites && favorites[doc.id] === true) {
listing.saved = true;
}
data.push({ ...listing, id: doc.id });
});
callback(data);
})
);
}
You can combine your queries via this way if you want to have it optional:
let query = listingsRef.where('isApproved', '==', isApproved)
if (categoryId) {
query = query.where('categoryID', '==', categoryId)
}
if (categoryId2) {
query = query.where('categoryID2', '==', categoryId2)
}
query.onSnapshot...

setinterval function is running infinitely

const interval = setInterval(() => {
fire.database().ref().child(getpath())
.once("value",
(snapshot) => {
let item = snapshot.val()
console.log(item)
if (item !== null) {
let array = [];
Object.
keys(item)
.forEach(i => array.push(item[i]));
setCard1(array);
}
console.log(item, "item")
if (item !== null) {
itemlen = 7 //length of object I get from valid result
//stop polling for results
console.log(itemlen, "should clear")
}
else {
console.log("polling")
}
})
}, 1000)
console.log("comingout")
if (itemlen !== 0) {
console.log("goingIn")
clearInterval(interval);
}
}, [prefVar]);
expected clearinterval to stop the setinterval function but it is running continuosly and not stopping
itemlen is getting non zero values.Is there a better way of implementing this ?
I want stop useEffect once I get valid value from db.My code inside the for setinterval selects a random path and retrieve that path only problem is that sometimes the path is empty,thus using setInterval
I would create two state items, one which keeps the interval and the other which stores itemlen, and would use another useEffect to listen on changes to itemlen, and when it is not 0, the interval should clear. Also, I would check if there is another interval running before you start another one.
const [itemlen, setItemlen] = useState(0);
const [pollingInterval, setPollingInterval] = useState(null);
useEffect(() => {
if (pollingInterval === null) {
setPollingInterval(setInterval(() => {
fire.database().ref().child(getpath())
.once("value",
(snapshot) => {
let item = snapshot.val()
console.log(item)
if (item !== null) {
let array = [];
Object.
keys(item)
.forEach(i => array.push(item[i]));
setCard1(array);
}
console.log(item, "item")
if (item !== null) {
setItemlen(7);
console.log("should clear")
} else {
console.log("polling")
}
})
}, 1000));
}
}, [prefVar]);
useEffect(() => {
if (itemlen !== 0 && pollingInterval !== null) {
clearInterval(pollingInterval);
setPollingInterval(null);
}
}, [itemlen])

Vue.js - Element UI - get the state of form validation

Steps to reproduce
The recurrence link is this: https://stackblitz.com/edit/typescript-vuejs-element-3kko7a
password input 2
username input 11
Change username to 2// should be able to submit, but not
Expected: formvalid = true
Validate Code here:
checkForm() {
// console.log('validate runs');
// #ts-ignore
const fields = this.$refs.ruleForm.fields;
if (fields.find((f) => f.validateState === 'validating')) {
setTimeout(() => {
this.checkForm();
}, 100);
}
this.formValid = fields.reduce((acc, f) => {
const valid = (f.isRequired && f.validateState === 'success');
const notErroring = (!f.isRequired && f.validateState !== 'error');
return acc && (valid || notErroring);
}, true);
console.log('valid:', this.$data.formValid);
}
Basically you watch ruleForm - so everytime ruleForm changes you trigger checkform - but your validtor triggers on blur after you set ruleForm so you first test then turn valid. change this into a getter:
get formValid(){
const fields = this.$refs.ruleForm.fields || [];
if (fields.find((f) => f.validateState === 'validating')) {
setTimeout(() => {
this.checkForm();
}, 100);
}
return fields.reduce((acc, f) => {
const valid = (f.isRequired && f.validateState === 'success');
const notErroring = (!f.isRequired && f.validateState !== 'error');
return acc && (valid || notErroring);
}, fields.length > 0);
}

react-native-numeric-input change event is not triggered

I'm currently working on a react project using multiple libraries including react-native-numeric-input which for some reason have a lot of unexpected behaviours.
Last night I had everything working as it should be but when I can to take another look the numeric input + and - buttons are not responding to any of the clicks, I even added a console.log to the onChange prop to test if the value is not changing or the event is not triggered and i didn't get anything.
this the numeric input:
<NumericInput
onChange={num => {
console.log(num);
this.setState({ updateItem: num}, this.saveChangedConfigs);
console.log('input', this.state);
}}
value={this.state.updateItem}
totalWidth={configValues.inw}
totalHeight={configValues.inh}
initValue={this.state.updateItem}
inputStyle={{ backgroundColor: '#f4f4f4'}}
containerStyle={styles.updateValue}
minValue={1}
/>
these are the two methods that change the state:
saveChangedConfigs = async () => {
try {
this.props.saveConfigs({
stockpile: this.state.updateItem.toString(),
data: this.state.updateData.toString(),
delete: this.state.emptyFiles.toString(),
autoUpdate: this.state.autoUpdate.toString(),
language: this.state.language
})
await this.initConfigs();
} catch (error) {
console.log('save err', error);
}
}
and
initConfigs = async () => {
const configs = await AsyncStorage.multiGet([
'updateStockpile',
'updateData',
'emptyPhone',
'language',
'autoUpdate'
])
console.log("configs", configs)
const confs = {
stockpile: this.props.config.stockpile,
autoUpdate: this.props.config.autoUpdate,
language: this.props.config.language,
data: this.props.config.data,
delete: this.props.config.delete
}
await configs.map(conf => {
switch(conf[0]){
case 'updateStockpile': if(conf[1] !== null) confs.stockpile = conf[1]; break;
case 'updateData': if(conf[1] !== null) confs.data = conf[1]; break;
case 'emptyPhone': if(conf[1] !== null) confs.delete = conf[1]; break;
case 'language': if(conf[1] !== null) confs.language = conf[1]; break;
case 'autoUpdate': if(conf[1] !== null) confs.autoUpdate = conf[1]; break;
}
})
await this.props.initConfigs(confs);
await this.setState({
language: confs.language,
updateItem: Number(confs.stockpile),
updateData: Number(confs.data),
emptyFiles: Number(confs.delete),
autoUpdate: confs.autoUpdate
});
}
this is my initial state:
this.state = {
language: this.props.config.language,
updateItem: Number(this.props.config.stockpile),
updateData: Number(this.props.config.data),
emptyFiles: Number(this.props.config.delete),
autoUpdate: this.props.config.autoUpdate
}
Hope you guys can help me out with this or maybe suggest an alternative if you know about one.