Annotation based triggers that automatically hook observers into the Android lifecycle.
- Pick and choose different lifecycle events for each annotated observer
- Leverages
android.arch.lifecycle
components and is compatible with the very sameLifecycle.Event
s - Automatic binding in one step
- Works out of the box with
Activity
andFragment
classes
In order to properly facilitate auto binding, your observers need two things:
- Your observers needs to implement
LifecycleEventObserver
- Your observers needs to be initialized before you call
LifecycleBinder.bind(...)
Once you meet those prerequisites, you can tag any of your observers like this:
public class MyActivity extends AppCompatActivity {
// myObserver will automatically trigger during onStart(...)
@LifecycleAware(Lifecycle.Event.ON_START)
LifecycleEventObserver myObserver = new MyObserver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// bind all observers to this Activity's lifecycle
LifecycleBinder.bind(this);
}
}
It is possible quickly register any variable as LifecycleAware
as long as you provide the method that should be called during the lifecycle event.
// myList will automatically clear() during onResume(...)
@LifecycleAware(value = Lifecycle.Event.ON_RESUME, method = "clear")
List<String> myList = new ArrayList<>();
In the case that your target class is not a core Android component (ie not an Activity
),
you can still perform auto binding. You just need to properly provide the target when binding:
class MyTarget {
@LifecycleAware(Lifecycle.Event.ON_DESTROY)
LifecycleEventObserver observer = new MyObserver();
}
MyTarget myTarget = new MyTarget();
LifecycleBinder.bind(myTarget, MyActivity.this);
In the case that your Lifecycle
is customized, you can still perform auto binding.
You just need to properly provide the LifecycleOwner
or Lifecycle
when binding:
LifecycleBinder.bind(someTarget, myCustomOwner);
// or
LifecycleBinder.bind(someTarget, myCustomLifecycle);
You can find examples in the included sample app.
dependencies {
implementation 'com.jzallas:lifecycleaware:0.1.0'
annotationProcessor 'com.jzallas:lifecycleaware-compiler:0.1.0'
}
Copyright 2017 Jon Zallas
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.