I know there are similar questions but it still doesn't answer my question in the manner I need for my current situation.
I have three activity presenters that each need to call a certain data remotely which will therefore call the activity presenter back when data arrives. To create this data listener I created an interface listener and since all three Presenters ask for the same data and retrieve it, all three presenters implement this interface listener.
Interface listener:
interface ListenerInterface {
onGotData();
}
Presenter one:
class PresenterOne implements ListenerInterface{
public void getData() {
DataManager dataManager = new DataManager();
dataManager.getData(this);
}
#Override
public void onGotData(Data data) {
//Do something with data
}
}
Presenter two very similar to presenter one:
class PresenterTwo implements ListenerInterface{
public void getData() {
DataManager dataManager = new DataManager();
dataManager.getData(this);
}
#Override
public void onGotData(Data data) {
//Do something with data
}
}
Assume Presenter three is exactly the same as the previous. The data manager class:
class DataManager {
public void getData(final ListenerInterface listener) {
//Gets data
addOnCompleteListener(new OnCompleteListener<Data data > () {
#Override
public void onComplete (#NonNull DataCall < Data > dataCall) {
listener.onGotData(dataCall.getResults());
}
});
}
}
Would doing so someone call all three presenters since the interface is the one doing the calling or only call the presenter that is passed? Is there anything I should worry about if I followed way? If anyone who knows the Android framework well could provide a detailed answer so I could learn from it more that would be great.
The reason I want to do this is I want to communicate through interfaces between classes.
Sorry if this question is simple for some people but I am still learning.
Thank you very much in advance.
you can use RxBus implementation to make global event (e.g. your onGotData).
First you have to create RxBus class.
public class RxBus {
private static RxBus instance;
private PublishSubject<Event> subject = PublishSubject.create();
public static synchronized RxBus getInstance() {
if (instance == null) {
instance = new RxBus();
}
return instance;
}
private RxBus(){}
public void postEvent(Event event){
subject.onNext(event);
}
public Observable<Event> getEvents(){
return subject;
}
}
And now, you should subscribe to it in BaseActivity or something like this (depends or your project structure).
private RxBus rxbus;
private Subscription rxBusSubscription;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rxBus = RxBus.getInstance();
}
#Override
protected void onResume() {
super.onResume();
if (shouldSubscribeRxBus()) {
rxBusSubscription = rxBus.getEvents()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> {
if (event.getEventType() == Event.EventType.DATA_RECEIVED) {
onGotData(data);
}
});
}
}
Now implement you onGotData as you want.
When you catch data received call:
class DataManager {
public void getData(final ListenerInterface listener) {
//Gets data
addOnCompleteListener(new OnCompleteListener<Data data > () {
#Override
public void onComplete (#NonNull DataCall < Data > dataCall) {
RxBus.getInstance().postEvent(new GotDataEvent(dataCall.getResults()));
}
});
}
}
You can create your Event classes structure as you want.
Related
In the MessageFeedActivity onCreate method it load feeds by calling getMessageTypes method of CTFeedAPI class.
public class MessageFeedActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Setting the listener
CTFeedAPI ctFeedAPI = new CTFeedAPI(new CTFeedAPI.CTFeedAPIListener() {
#Override
public void feedAPISuccessListener(Object object) {
// Handle Success
}
#Override
public void feedAPIErrorListener(int error) {
// Handle Error
}
});
ctFeedAPI.getMessageTypes();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
and wait for CTFeedAPIListener response. And CTFeedAPI class make network request by calling performRequest method of NetworkRequest class as
public class CTFeedAPI implements NetworkListener {
private CTFeedAPIListener apiListener;
public CTFeedAPI(CTFeedAPIListener feedAPIListener) {
apiListener = feedAPIListener;
}
public void getMessageTypes() {
Map < String, String > params = new HashMap < > ();
params.put("f", "GetMessageTypes");
NetworkRequest networkRequest = new NetworkRequest(this);
networkRequest.performRequest();
}
public interface CTFeedAPIListener {
void feedAPISuccessListener(Object object);
void feedAPIErrorListener(int error);
}
}
and wait for NetworkListener response
public class NetworkRequest {
private NetworkListener mListener;
public interface NetworkListener {
void networkReqSuccessListener(String cacheKey, String tag, String response);
void networkReqErrorListener(String tag, int error);
}
public NetworkRequest(NetworkListener listener) {
this.mListener = listener;
}
public void performRequest(
// Perform Network Requests and respond as
if (mListener != null) {
if (success) {
mListener.networkReqSuccessListener(getUrl(), getTag(), response);
} else {
mListener.networkReqErrorListener(getTag(), err_msg);
}
}
}
When users press back key, before destroy the MessageFeedActivity, the system call 'onDestroy' method. And Unfortunately, because the background thread (performRequest method in NetworkRequest class) is still keep a reference to it, leak occurs.
So how to implement CTFeedAPIListener reference in MessageFeedActivity to remove leak.
In this design not only you will leak memory but also your code would be highly coupled and very hard to test; prone to bugs that are hard to detect. I would suggest you implement MVP or similar architecture. Your activity should never know anything about your network layer. Add a presenter layer that is responsible to request something on behalf of your activity and use interface to update your activity. Your presenter should access a business entity that is mapped from the response of repository layer, that is responsible for network or Db access and return values to the client presenter. This way your presenter and business logic layers would be decoupled and easy to test independently. In the future if business requirements change, your changes don't affect other layers. Please see this article for more information on the subject.
Weak reference objects, which do not prevent their referents from
being made finalizable, finalized, and then reclaimed. Weak references
are most often used to implement canonicalizing mappings.
Suppose that the garbage collector determines at a certain point in
time that an object is weakly reachable. At that time it will
atomically clear all weak references to that object and all weak
references to any other weakly-reachable objects from which that
object is reachable through a chain of strong and soft references. At
the same time it will declare all of the formerly weakly-reachable
objects to be finalizable. At the same time or at some later time it
will enqueue those newly-cleared weak references that are registered
with reference queues.
You can use Weak Reference:
import java.lang.ref.WeakReference;
public class NetworkRequest {
public interface NetworkListener {
void networkReqSuccessListener(String cacheKey, String tag, String response);
void networkReqErrorListener(String tag, int error);
}
private WeakReference<NetworkListener> mListener;
public NetworkRequest(NetworkListener listener) {
this.mListener = new WeakReference<NetworkListener>(listener);
}
public void performRequest(){
// Perform Network Requests and respond as
NetworkListener listener = mListener.get();
if (listener != null) {
if (success) listener.networkReqSuccessListener(getUrl(), getTag(), response);
else listener.networkReqErrorListener(getTag(), err_msg);
}
}
}
public class CTFeedAPI implements NetworkListener {
private WeakReference<CTFeedAPIListener> apiListener;
public CTFeedAPI(CTFeedAPIListener feedAPIListener) {
apiListener = new WeakReference<>(feedAPIListener);
}
public void getMessageTypes() {
Map < String, String > params = new HashMap < > ();
params.put("f", "GetMessageTypes");
NetworkRequest networkRequest = new NetworkRequest(this);
networkRequest.performRequest();
}
public interface CTFeedAPIListener {
void feedAPISuccessListener(Object object);
void feedAPIErrorListener(int error);
}
}
save CTFeedAPI and CTFeedAPIListener as instance variable of MessageFeedActivity to prevent GC collecting them when activity is presented:
public class MessageFeedActivity extends AppCompatActivity {
private CTFeedAPI ctFeedAPI = null;// keeping a reference to CTFeedAPI
private CTFeedAPIListener listener = null;// keeping a reference to listener
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Setting the listener
listener = new CTFeedAPI.CTFeedAPIListener() {
#Override
public void feedAPISuccessListener(Object object) {
// Handle Success
}
#Override
public void feedAPIErrorListener(int error) {
// Handle Error
}
});
ctFeedAPI = new CTFeedAPI(listener);
ctFeedAPI.getMessageTypes();
}
So I'm using the Observer pattern in my app in order to get notified of changes in another class without having to look for them.
I have a Singleton class which extends Observable. Inside this class I have two CountDownTimer type variables. Eachs of these contains two methods: onTick() and onFinished().
Let's call those Timers A and B for the sake of simplicity.
Every time A.onTick(), A.onFinished(), B.onTick(), B.onFinished() are called, I must call notifyObservers() to notify my Observer that something has changed.
Until here everything works fine. The problem is that I know something has changed, but I don't know what exactly has changed. Depending on which one notified me, I must execute some code on the Observer side.
How do I know which of these methods notified me?
Use LiveData instead of Observable. LiveData is quite useful because not only it's observable but also it binds to your activity's lifecycle so you don't have to worry about handling it yourself.
Maybe this example will help you:
public class MyTimerWrapper {
public static MyTimerWrapper getInstance() {
// Your singleton logic
createTimers();
return instance;
}
private CountDownTimer timerA;
private CountDownTimer timerB;
private MutableLiveData<TimerEvent> timerALiveData = new MutableLiveData<TimerEvent>();
private MutableLiveData<TimerEvent> timerBLiveData = new MutableLiveData<TimerEvent>();
public LiveData<TimerEvent> startTimerA() {
timerA.start();
return timerALiveData;
}
public LiveData<TimerEvent> startTimerB() {
timerB.start();
return timerBLiveData;
}
private void createTimers() {
createTimerA();
createTimerB();
}
private void createTimerA() {
timerA = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
// If you're running on another thread
timerALiveData.postValue(TimerEvent.TICK);
// Otherwise
timerALiveData.setValue(TimerEvent.TICK);
}
#Override
public void onFinish() {
// If you're running on another thread
timerALiveData.postValue(TimerEvent.FINISH);
// Otherwise
timerALiveData.setValue(TimerEvent.FINISH);
}
}
}
private void createTimerB() {
// Same as createTimerA, but with timerB
}
}
public enum TimerEvent {
TICK,
FINISH
}
Now to observe that data in your activity:
MyTimerWrapper timerWrapper = MyTimerWrapper.getInstance();
timerWrapper.startTimerA().observe(this, new Observer {
#Override
public void onChanged(TimerEvent timerEvent) {
// Here you'll be able to see whether timerA is ticking or finished
}
})
You can create a custom EventType class and pass it to Observable.notifyObservers(Object arg):
public class EventType {
String eventType; //"onTick" or "onFinish"
TimerType timerType;
EventType(String eventType, TimerType timerType){
this.eventType = eventType;
this.timerType = timerType;
}
}
TimerType is an enum type:
public enum TimerType {
A,
B;
}
and create TimerA and TimerB classes extending CountDownTimer:
private class TimerA extends CountDownTimer {
final EventType onTickEvent = new EventType("onTick", TimerType.A);
final EventType onFinishEvent = new EventType("onFinish", TimerType.A);
#Override
public void onTick(long millisUntilFinished) {
notifyObservers(onTickEvent);
}
#Override
public void onFinish() {
notifyObservers(onFinishEvent)
}
}
The Observerwill receive the EventType instance via its update(Observable o, Object arg); in the arg argument
Firebase -> PhoneAuthProvider -> VerifyPhoneNumber is leaking. I believe, it might be OnVerificationStateChangedCallbacks, which we are sending on call to verifyPhoneNumber.
Steps to reproduce:
Launch the app
Select "PhoneAuthActivity" for phone based authentication
Send Phone Number.
Click back.
When clicking back, the leaked memory appear
Does someone have the same problem? any solution?
public void FirebasePhoneUser(String phoneNumber) {
mCallback = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Log.d("Completed","");
}
#Override
public void onVerificationFailed(FirebaseException e) {
Log.d("Error","");
}
#Override
public void onCodeSent(String verificationId,
PhoneAuthProvider.ForceResendingToken forceResendingToken) {
Log.d("onCodeSent", "");
}
};
phoneAuthProvider = PhoneAuthProvider.getInstance();
phoneAuthProvider.verifyPhoneNumber(
phoneNumber,
30,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallback
);
}
Given that API is terrible and there's no option to unsubscribe, you have several options to work this around.
Proxy or Decorator. You create another OnVerificationStateChangedCallbacks which delegates method calls to another instance:
// this class must be either top-level or 'static'!
public /*static*/ final class DelegatingVerificationStateCallbacks
extends PhoneAuthProvider.OnVerificationStateChangedCallbacks
implements Closeable {
#Nullable private PhoneAuthProvider.OnVerificationStateChangedCallbacks delegate;
public DelegatingVerificationStateCallbacks(
#NonNull PhoneAuthProvider.OnVerificationStateChangedCallbacks delegate
) {
this.delegate = delegate;
}
#Override public void onCodeSent(
#NonNull String verificationId,
#NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken
) {
if (delegate != null) delegate.onCodeSent(verificationId, forceResendingToken);
}
#Override public void onCodeAutoRetrievalTimeOut(#NonNull String s) {
if (delegate != null) delegate.onCodeAutoRetrievalTimeOut(s);
}
#Override public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
if (delegate != null) delegate.onVerificationCompleted(phoneAuthCredential);
}
#Override public void onVerificationFailed(#NonNull FirebaseException e) {
if (delegate != null) delegate.onVerificationFailed(e);
}
#Override public void close() {
delegate = null;
}
}
I've implemented Closeable for cleanup but you could implement RxJava's Disposable or whatever instead.
The usage pattern here is obvious and well-known:
public final class SomeScreen extends ActivityOrFragmentOrControllerOrWhatever {
private final ArrayList<Closeable> disposeBag = new ArrayList<>();
private void performAuth() {
DelegatingVerificationStateCallbacks callbacks =
new DelegatingVerificationStateCallbacks(
new OnVerificationStateChangedCallbacks() { … }
);
disposeBag.add(callbacks);
phoneAuthProvider.verifyPhoneNumber(…, callbacks);
}
#Override protected void onDestroy() {
for (Closeable c : disposeBag) {
try { c.close(); }
catch (IOException ignored) { }
}
disposeBag.clear();
}
}
Result: Firebase leaks a reference to empty and cheap DelegatingVerificationStateCallbacks, not to Activity.
Nulling references out yourself. You can take approach presented above to clear your own references to Activity. This implies these reference must be explicit, i. e. class must not be anonymous or inner to your activity. You must take full control of class constructor and fields, top-level class or nested static class is a good fit.
Weak reference. This is less explicit and involves some indirection but still works: you instantiate top-level or nested static class, pass Activity to constructor, wrap it in a WeakReference, and assign to a field. That's all, after some time WeakReference#get will start returning null.
Reflection. Very bad and unstable option which could help in some other situations. Sometimes your Activity could be leaked by Android SDK or vendor-specific code, and options from above don't apply. Then you can null out some private fields yourself. Don't do this for Firebase.
I am developing android application and I want to refresh viewModel livedata from second activity. When I get back to first activity data is not refreshed.
FirstActivity:
mViewModel = ViewModelProviders.of(this).get(MenuViewModel.class);
mViewModel.getMenus().observe(this, menuResponse -> {
if (menuResponse != null) {
resMenus.addAll(menuResponse.getMenus());
progressBar.setVisibility(View.GONE);
mAdapter.notifyDataSetChanged();
}
});
MenuViewModel:
public class MenuViewModel extends AndroidViewModel {
private MutableLiveData<MenuResponse> restMenuData;
private MenusRepository mRepository;
public MainActivityViewModel(#NonNull Application application) {
super(application);
mRepository = MenusRepository.getInstance(application);
restMenuData = mRepository.getMenus();
}
public LiveData<MenuResponse> getMenus() {
return restMenuData;
}
}
MenusRepository
private MenusRepository(Context context) {
apiRequest= RetrofitInstance.getInstance(context).getApiRequest();
}
public synchronized static MenusRepository getInstance(Context context) {
if (projectRepository == null) {
projectRepository = new MenusRepository(context);
}
return projectRepository;
}
public MutableLiveData<MenuResponse> getMenus() {
final MutableLiveData<MenuResponse> data = new MutableLiveData<>();
apiRequest.getMenus().enqueue(new Callback<MenuResponse>() {
#Override
public void onResponse(#NonNull Call<MenuResponse> call, #NonNull Response<MenuResponse> response) {
if (response.isSuccessful() && response.body() != null) {
data.setValue(response.body());
}
}
#Override
public void onFailure(#NonNull Call<MenuResponse> call, #NonNull Throwable t) {
data.setValue(null);
}
});
return data;
}
SecondActivity:
MenuViewModel mViewModel = ViewModelProviders.of(Objects.requireNonNull(SecondActivity.this)).get(MenuViewModel.class);
mViewModel.getMenus();
// This line not refresh menus
I except to refresh data from viewmodel, but it return old data.
How can I refresh viewmodel data in best practices?
MenusRepository.getMenus() methods creates a new instance of LiveData for every call. This is not the correct way to go about it.
You should have only one instance of LiveData and different objects subscribe to it (activity, viewModel, etc).
What you could do is - create a singleton of MenusRepository (which I think you have already done). Create one instance of MutableLiveData only and use it to update the data.
class MenusRepository {
private val liveData = MutableLiveData<MenuResponse>()
fun getMenus() {
// Your api call. Do not create a new instance of the livedata.
}
fun menus(): LiveData<MenuResponse> {
return liveData
}
fun update(data: MenuResponse) {
liveData.post(data)
}
This code is in Kotlin, but it applies similarly to Java as well.
You can update method to post an update to liveData. When you update it, all the observers will receive the new data. Use MenusRepository.menus() to access LiveData in your ViewModel.
Update
Your MenuRepository class could be like this.
private final MutableLiveData<MenuResponse> liveData = new MutableData<>();
private MenusRepository(Context context) {
apiRequest= RetrofitInstance.getInstance(context).getApiRequest();
}
public synchronized static MenusRepository getInstance(Context context) {
if (projectRepository == null) {
projectRepository = new MenusRepository(context);
}
return projectRepository;
}
public MutableLiveData<MenuResponse> loadMenus() {
apiRequest.getMenus().enqueue(new Callback<MenuResponse>() {
#Override
public void onResponse(#NonNull Call<MenuResponse> call, #NonNull Response<MenuResponse> response) {
if (response.isSuccessful() && response.body() != null) {
liveData.setValue(response.body());
}
}
#Override
public void onFailure(#NonNull Call<MenuResponse> call, #NonNull Throwable t) {
liveData.setValue(null);
}
});
}
public LiveData<MenuResponse> getMenus() {
return liveData;
}
public void updateData(response: MenuResponse) {
liveData.postValue(response);
}
When you want to update the data manually (from another activity),
use menuRepository.update() method. This will post the data to your LiveData which will update all its observers, ie. the ViewModel.
Call menuRepository.loadMenu() when you want to get the data using API.
Use menuRepository.getMenus() to get the LiveData and attach your observers.
Since MenuRepository is a singleton, there's only one instance of LiveData. When you will post an update to this instance of LiveData, all the observers will receive the new data.
public class MenuViewModel extends AndroidViewModel {
private MutableLiveData<MenuResponse> restMenuData;
private MenusRepository mRepository;
public MainActivityViewModel(#NonNull Application application) {
super(application);
mRepository = MenusRepository.getInstance(application);
restMenuData = mRepository.getMenus();
}
public LiveData<MenuResponse> getMenus() {
restMenuData = new MutableLiveData<>();
return restMenuData;
}
}
Change the View model code as above.
So that the live data is always cleared before returning to activity.
I am developing an app where I am using clean architecture. In presenter, when something comes to method onCompleted then I must call function from Main activity.
this is my Presenter:
public class CheckInPresenter implements Presenter {
UseCase postCheckInUseCase;
Context context;
#Inject
CheckInPresenter(#Named("putCheckIn") UseCase postCheckInUseCase){
this.postCheckInUseCase = postCheckInUseCase;
}
public void initialize(){this.initializeCheckIn();}
public void initializeCheckIn(){this.putCheckIn();}
public void putCheckIn(){
this.postCheckInUseCase.execute(new CheckInSubscriber());
}
#Override
public void resume() {
}
#Override
public void pause() {
}
#Override
public void destroy() {
}
private final class CheckInSubscriber extends DefaultSubscriber<EventEntity>{
#Override
public void onCompleted() {
Log.d("onCompleted", "OnCompleted");
}
#Override
public void onError(Throwable e) {
Log.d("onError", "OnError: " + e.getMessage());
}
#Override
public void onNext(EventEntity eventEntity) {
Log.d("onNext", "OnNext");
}
}
}
And this is my function from MainActivity that I have to call:
public void getDataForToolbar() {
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.Account_json), Context.MODE_PRIVATE);
final String account = sharedPreferences.getString(getResources().getString(R.string.account_json), null);
if (account != null) {
Gson gson = new Gson();
mAccount = gson.fromJson(account, AccountModel.class);
for (CompanyModel com : mAccount.getCompanies()) {
String name = com.getName();
company_name.setText(name);
logo_url = com.getLogo_url();
}
if (logo_url == null || logo_url.isEmpty()) {
Picasso
.with(this)
.load(R.drawable.default_company)
.resize(70, 58)
.transform(new RoundedTransformation(8, 0))
.into(toolbarImage);
} else {
picassoLoader(this, toolbarImage, logo_url);
}
String username = mAccount.getUsername();
if(mAccount.getStatus()){
aUsername.setText(username + "/" + getResources().getString(R.string.on_duty));
aUsername.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorGreen));
}else{
aUsername.setText(username + "/" + getResources().getString(R.string.off_duty));
aUsername.setBackgroundColor(ContextCompat.getColor(mContext, R.color.colorWhite));
}
}
}
Could someone helps me how to call this function into my onCompleted method in Presenter? Thanks in advance.
If you want to call some Activity's function from another object, you'll have to pass Activity's reference to that object. This means that you need to add Activity parameter to presenter's constructor.
Side note
I know that what you're implementing is called a "clean architecture" in many places (including the official MVP tutorials by Google), but you might want to read my posts on the subject in order to get an alternative view on what "clean" on Android should look like.
Why activities in Android are not UI elements
MVC and MVP architectural patterns in Android
Create interface IView and make your Activity to implement it.
In IView create method void getDataForToolbar();
I see #Inject annotation in your CheckInPresenter, so if you are using Dagger 2, update you Dagger module's constructor with IView, create a provider method for it and provide it for CheckInPresenter in this module.
Place IView in constructor of CheckInPresenter and update provider method for CheckInPresenter in Dagger module and Dagger component initialization in your Activity.
For example, it might look like this:
public class YourActivity implements IView {
...
}
#Module
public class YourModule {
private IView view;
public YourModule(IView view) {
this.view = view;
}
#Provides
public IView provideView() {
return view;
}
#Provides
#YourScope
public Presenter providePresenter() {
return new YourPresenter(view);
}
}
Just complete your existing Presenter and Module with IView.
After that call in your onCompleted method view.getDataForToolbar().