Skip to content

Commit

Permalink
Actually allow getting the retained object
Browse files Browse the repository at this point in the history
  • Loading branch information
Zhuinden committed Mar 8, 2021
1 parent 514c68b commit 6379cfe
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
-Simple Stack 2.6.0 (2021-03-08)
--------------------------------

- ADD: `Backstack.addRetainedObject(objectTag, retainedObject)`, `Backstack.hasRetainedObject(objectTag)`, `Backstack.removeRetainedObject(objectTag)`.
- ADD: `Backstack.addRetainedObject(objectTag, retainedObject)`, `Backstack.hasRetainedObject(objectTag)`, `Backstack.removeRetainedObject(objectTag)`, `Backstack.getRetainedObject(objectTag)`.

This allows simpler way of persisting an object instance across configuration changes.

Expand Down
19 changes: 19 additions & 0 deletions simple-stack/src/main/java/com/zhuinden/simplestack/Backstack.java
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,25 @@ public boolean hasRetainedObject(@Nonnull String objectTag) {
return retainedObjects.containsKey(objectTag);
}

/**
* Gets the retained object with the given tag. Throws if does not exist.
*
* @param objectTag the object tag
* @param <T> the type of the retained object
* @return the retained object
*/
@Nonnull
public <T> T getRetainedObject(@Nonnull String objectTag) {
assertCorrectThread();

if (!retainedObjects.containsKey(objectTag)) {
throw new IllegalArgumentException("Retained object with tag [" + objectTag + "] was not found.!");
}

//noinspection unchecked
return (T) retainedObjects.get(objectTag);
}

/**
* Add an object as a retained object. This will make it persist across configuration changes.
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -897,6 +897,16 @@ public void retainedObjectCannotBeRegisteredWithSameKey() {
// OK
}

try {
backstack.getRetainedObject("blah");
Assert.fail();
} catch (IllegalArgumentException e) {
// OK
}

Object currentObj = backstack.getRetainedObject("duplicateKey");
assertThat(currentObj).isSameAs(retainedObject);

Object obj = backstack.removeRetainedObject("duplicateKey");
assertThat(obj).isSameAs(retainedObject);
}
Expand Down

0 comments on commit 6379cfe

Please sign in to comment.