Skip to content

Instantly share code, notes, and snippets.

@NinoDLC
Created August 23, 2022 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NinoDLC/5127a89de0617b0bc4d1473b55c6cf90 to your computer and use it in GitHub Desktop.
Save NinoDLC/5127a89de0617b0bc4d1473b55c6cf90 to your computer and use it in GitHub Desktop.
OC - P7: Go4Lunch - MVVM Example for DispatcherActivity
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="fr.delcey.go4lunch">
<application
...
>
<activity
android:name=".view.dispatcher.DispatcherActivity"
android:theme="@style/Theme.Go4Lunch.NoActionBar.Transparent">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
...
</application>
</manifest>
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import fr.delcey.go4lunch.view.ViewModelFactory;
public class DispatcherActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// No "setContentView(int)" to have a fully transparent and performant Activity
DispatcherViewModel viewModel = new ViewModelProvider(this, ViewModelFactory.getInstance()).get(DispatcherViewModel.class);
viewModel.getViewActionSingleLiveEvent().observe(this, dispatcherViewAction -> {
switch (dispatcherViewAction) {
case GO_TO_CONNECT_SCREEN:
startActivity(new Intent(DispatcherActivity.this, OAuthActivity.class));
finish();
break;
case GO_TO_MAIN_SCREEN:
startActivity(new Intent(DispatcherActivity.this, MainActivity.class));
finish();
break;
}
});
}
}
public enum DispatcherViewAction {
GO_TO_CONNECT_SCREEN,
GO_TO_MAIN_SCREEN
}
import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModel;
import com.google.firebase.auth.FirebaseAuth;
import fr.delcey.go4lunch.view.utils.SingleLiveEvent;
public class DispatcherViewModel extends ViewModel {
@NonNull
private final SingleLiveEvent<DispatcherViewAction> viewActionSingleLiveEvent = new SingleLiveEvent<>();
public DispatcherViewModel(@NonNull FirebaseAuth firebaseAuth) {
// User not connected
if (firebaseAuth.getCurrentUser() == null) {
viewActionSingleLiveEvent.setValue(DispatcherViewAction.GO_TO_CONNECT_SCREEN);
} else {
viewActionSingleLiveEvent.setValue(DispatcherViewAction.GO_TO_MAIN_SCREEN);
}
}
@NonNull
public SingleLiveEvent<DispatcherViewAction> getViewActionSingleLiveEvent() {
return viewActionSingleLiveEvent;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment