Reputation: 257
I have a View that converts some text to a localised version of that text using an API. This works if the View is visible in the layout because once the View gets destroy onDetachedFromWindow()
gets called. However if the View is invisible and never gets attached to the Window onDetachedFromWindow()
never gets called.
I tried performing the localisation in onAttachedToWindow()
but this ends up causing the Text to not be displayed/cut off.
public class LocalisedTextView extends TextView {
@Override
protected void onFinishInflate() {
super.onFinishInflate();
setLocalisedText(label);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
subscription = null;
}
}
public void setLocalisedText(String label) {
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
subscription = null;
}
subscription = localisationService.get(label)
.observeOn(Scheduler.ui())
.subscribe(this::setText;
}
}
This causes a memory leak in the case where the View is never made visible/put onto the Window.
So I was wondering what the best approach would be to handle subscriptions on Views that may never be attached to the window?
Upvotes: 2
Views: 815
Reputation: 93678
A graphical element like a view should not be performing any logic that doesn't directly effect drawing. It should not be localizing text, instead localized text should be passed in to it.
Upvotes: 3