Search in sources :

Example 1 with NonNull

use of io.reactivex.rxjava3.annotations.NonNull in project Tusky by Vavassor.

the class NotificationsFragment method onCreateView.

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_timeline_notifications, container, false);
    // from inflater to silence warning
    @NonNull Context context = inflater.getContext();
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    boolean showNotificationsFilterSetting = preferences.getBoolean("showNotificationsFilter", true);
    // Clear notifications on filter visibility change to force refresh
    if (showNotificationsFilterSetting != showNotificationsFilter)
        notifications.clear();
    showNotificationsFilter = showNotificationsFilterSetting;
    // Setup the SwipeRefreshLayout.
    swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
    recyclerView = rootView.findViewById(R.id.recyclerView);
    progressBar = rootView.findViewById(R.id.progressBar);
    statusView = rootView.findViewById(R.id.statusView);
    appBarOptions = rootView.findViewById(R.id.appBarOptions);
    swipeRefreshLayout.setOnRefreshListener(this);
    swipeRefreshLayout.setColorSchemeResources(R.color.tusky_blue);
    loadNotificationsFilter();
    // Setup the RecyclerView.
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(context);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAccessibilityDelegateCompat(new ListStatusAccessibilityDelegate(recyclerView, this, (pos) -> {
        NotificationViewData notification = notifications.getPairedItemOrNull(pos);
        // We support replies only for now
        if (notification instanceof NotificationViewData.Concrete) {
            return ((NotificationViewData.Concrete) notification).getStatusViewData();
        } else {
            return null;
        }
    }));
    recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
    StatusDisplayOptions statusDisplayOptions = new StatusDisplayOptions(preferences.getBoolean("animateGifAvatars", false), accountManager.getActiveAccount().getMediaPreviewEnabled(), preferences.getBoolean("absoluteTimeView", false), preferences.getBoolean("showBotOverlay", true), preferences.getBoolean("useBlurhash", true), CardViewMode.NONE, preferences.getBoolean("confirmReblogs", true), preferences.getBoolean("confirmFavourites", false), preferences.getBoolean(PrefKeys.WELLBEING_HIDE_STATS_POSTS, false), preferences.getBoolean(PrefKeys.ANIMATE_CUSTOM_EMOJIS, false));
    adapter = new NotificationsAdapter(accountManager.getActiveAccount().getAccountId(), dataSource, statusDisplayOptions, this, this, this);
    alwaysShowSensitiveMedia = accountManager.getActiveAccount().getAlwaysShowSensitiveMedia();
    alwaysOpenSpoiler = accountManager.getActiveAccount().getAlwaysOpenSpoiler();
    recyclerView.setAdapter(adapter);
    topLoading = false;
    bottomLoading = false;
    bottomId = null;
    updateAdapter();
    Button buttonClear = rootView.findViewById(R.id.buttonClear);
    buttonClear.setOnClickListener(v -> confirmClearNotifications());
    buttonFilter = rootView.findViewById(R.id.buttonFilter);
    buttonFilter.setOnClickListener(v -> showFilterMenu());
    if (notifications.isEmpty()) {
        swipeRefreshLayout.setEnabled(false);
        sendFetchNotificationsRequest(null, null, FetchEnd.BOTTOM, -1);
    } else {
        progressBar.setVisibility(View.GONE);
    }
    ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
    updateFilterVisibility();
    return rootView;
}
Also used : Context(android.content.Context) DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) Bundle(android.os.Bundle) ProgressBar(android.widget.ProgressBar) NonNull(androidx.annotation.NonNull) AsyncDifferConfig(androidx.recyclerview.widget.AsyncDifferConfig) SimpleItemAnimator(androidx.recyclerview.widget.SimpleItemAnimator) Utils(at.connyduck.sparkbutton.helpers.Utils) AccountActionListener(com.keylesspalace.tusky.interfaces.AccountActionListener) NotificationTypeConverterKt(com.keylesspalace.tusky.util.NotificationTypeConverterKt) AppBarLayout(com.google.android.material.appbar.AppBarLayout) BackgroundMessageView(com.keylesspalace.tusky.view.BackgroundMessageView) Locale(java.util.Locale) FloatingActionButton(com.google.android.material.floatingactionbutton.FloatingActionButton) ActionButtonActivity(com.keylesspalace.tusky.interfaces.ActionButtonActivity) View(android.view.View) Button(android.widget.Button) RecyclerView(androidx.recyclerview.widget.RecyclerView) Function(androidx.arch.core.util.Function) Log(android.util.Log) ViewDataUtils(com.keylesspalace.tusky.util.ViewDataUtils) StatusViewData(com.keylesspalace.tusky.viewdata.StatusViewData) CoordinatorLayout(androidx.coordinatorlayout.widget.CoordinatorLayout) ListUpdateCallback(androidx.recyclerview.widget.ListUpdateCallback) DiffUtil(androidx.recyclerview.widget.DiffUtil) PreferenceChangedEvent(com.keylesspalace.tusky.appstore.PreferenceChangedEvent) StatusActionListener(com.keylesspalace.tusky.interfaces.StatusActionListener) Set(java.util.Set) Function1(kotlin.jvm.functions.Function1) Relationship(com.keylesspalace.tusky.entity.Relationship) ViewGroup(android.view.ViewGroup) ReselectableFragment(com.keylesspalace.tusky.interfaces.ReselectableFragment) Objects(java.util.Objects) FavoriteEvent(com.keylesspalace.tusky.appstore.FavoriteEvent) StatusDisplayOptions(com.keylesspalace.tusky.util.StatusDisplayOptions) AndroidSchedulers(io.reactivex.rxjava3.android.schedulers.AndroidSchedulers) List(java.util.List) Unit(kotlin.Unit) AutoDispose.autoDisposable(autodispose2.AutoDispose.autoDisposable) Nullable(androidx.annotation.Nullable) Pair(androidx.core.util.Pair) Disposable(io.reactivex.rxjava3.disposables.Disposable) CollectionsKt(kotlin.collections.CollectionsKt) AsyncListDiffer(androidx.recyclerview.widget.AsyncListDiffer) ListView(android.widget.ListView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) StringUtils.isLessThan(com.keylesspalace.tusky.util.StringUtils.isLessThan) AccountEntity(com.keylesspalace.tusky.db.AccountEntity) Context(android.content.Context) BookmarkEvent(com.keylesspalace.tusky.appstore.BookmarkEvent) Notification(com.keylesspalace.tusky.entity.Notification) Single(io.reactivex.rxjava3.core.Single) AlertDialog(androidx.appcompat.app.AlertDialog) Status(com.keylesspalace.tusky.entity.Status) AndroidLifecycleScopeProvider.from(autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider.from) ReblogEvent(com.keylesspalace.tusky.appstore.ReblogEvent) Poll(com.keylesspalace.tusky.entity.Poll) NotificationViewData(com.keylesspalace.tusky.viewdata.NotificationViewData) PairedList(com.keylesspalace.tusky.util.PairedList) ArrayList(java.util.ArrayList) StatusBaseViewHolder(com.keylesspalace.tusky.adapter.StatusBaseViewHolder) PrefKeys(com.keylesspalace.tusky.settings.PrefKeys) HashSet(java.util.HashSet) Inject(javax.inject.Inject) Lifecycle(androidx.lifecycle.Lifecycle) CompositeDisposable(io.reactivex.rxjava3.disposables.CompositeDisposable) R(com.keylesspalace.tusky.R) CardViewMode(com.keylesspalace.tusky.util.CardViewMode) Observable(io.reactivex.rxjava3.core.Observable) AttachmentViewData(com.keylesspalace.tusky.viewdata.AttachmentViewData) DialogInterface(android.content.DialogInterface) ListStatusAccessibilityDelegate(com.keylesspalace.tusky.util.ListStatusAccessibilityDelegate) EventHub(com.keylesspalace.tusky.appstore.EventHub) BlockEvent(com.keylesspalace.tusky.appstore.BlockEvent) Iterator(java.util.Iterator) LayoutInflater(android.view.LayoutInflater) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) PopupWindow(android.widget.PopupWindow) HttpHeaderLink(com.keylesspalace.tusky.util.HttpHeaderLink) Either(com.keylesspalace.tusky.util.Either) IOException(java.io.IOException) TimeUnit(java.util.concurrent.TimeUnit) ArrayAdapter(android.widget.ArrayAdapter) SparseBooleanArray(android.util.SparseBooleanArray) PinEvent(com.keylesspalace.tusky.appstore.PinEvent) SharedPreferences(android.content.SharedPreferences) NotificationsAdapter(com.keylesspalace.tusky.adapter.NotificationsAdapter) PreferenceManager(androidx.preference.PreferenceManager) ListUtils(com.keylesspalace.tusky.util.ListUtils) AccountManager(com.keylesspalace.tusky.db.AccountManager) EndlessOnScrollListener(com.keylesspalace.tusky.view.EndlessOnScrollListener) Injectable(com.keylesspalace.tusky.di.Injectable) Activity(android.app.Activity) Collections(java.util.Collections) SimpleItemAnimator(androidx.recyclerview.widget.SimpleItemAnimator) SharedPreferences(android.content.SharedPreferences) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) DividerItemDecoration(androidx.recyclerview.widget.DividerItemDecoration) BackgroundMessageView(com.keylesspalace.tusky.view.BackgroundMessageView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) ListView(android.widget.ListView) StatusDisplayOptions(com.keylesspalace.tusky.util.StatusDisplayOptions) NotificationsAdapter(com.keylesspalace.tusky.adapter.NotificationsAdapter) ListStatusAccessibilityDelegate(com.keylesspalace.tusky.util.ListStatusAccessibilityDelegate) FloatingActionButton(com.google.android.material.floatingactionbutton.FloatingActionButton) Button(android.widget.Button) NonNull(androidx.annotation.NonNull) NotificationViewData(com.keylesspalace.tusky.viewdata.NotificationViewData) Nullable(androidx.annotation.Nullable)

Example 2 with NonNull

use of io.reactivex.rxjava3.annotations.NonNull in project Signal-Android by WhisperSystems.

the class BaseRegistrationLockFragment method onViewCreated.

@Override
@CallSuper
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    setDebugLogSubmitMultiTapView(view.findViewById(R.id.kbs_lock_pin_title));
    pinEntry = view.findViewById(R.id.kbs_lock_pin_input);
    pinButton = view.findViewById(R.id.kbs_lock_pin_confirm);
    errorLabel = view.findViewById(R.id.kbs_lock_pin_input_label);
    keyboardToggle = view.findViewById(R.id.kbs_lock_keyboard_toggle);
    forgotPin = view.findViewById(R.id.kbs_lock_forgot_pin);
    RegistrationLockFragmentArgs args = RegistrationLockFragmentArgs.fromBundle(requireArguments());
    timeRemaining = args.getTimeRemaining();
    forgotPin.setVisibility(View.GONE);
    forgotPin.setOnClickListener(v -> handleForgottenPin(timeRemaining));
    pinEntry.setImeOptions(EditorInfo.IME_ACTION_DONE);
    pinEntry.setOnEditorActionListener((v, actionId, event) -> {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            ViewUtil.hideKeyboard(requireContext(), v);
            handlePinEntry();
            return true;
        }
        return false;
    });
    enableAndFocusPinEntry();
    pinButton.setOnClickListener((v) -> {
        ViewUtil.hideKeyboard(requireContext(), pinEntry);
        handlePinEntry();
    });
    keyboardToggle.setOnClickListener((v) -> {
        PinKeyboardType keyboardType = getPinEntryKeyboardType();
        updateKeyboard(keyboardType.getOther());
        keyboardToggle.setText(resolveKeyboardToggleText(keyboardType));
    });
    PinKeyboardType keyboardType = getPinEntryKeyboardType().getOther();
    keyboardToggle.setText(resolveKeyboardToggleText(keyboardType));
    disposables.bindTo(getViewLifecycleOwner().getLifecycle());
    viewModel = getViewModel();
    viewModel.getLockedTimeRemaining().observe(getViewLifecycleOwner(), t -> timeRemaining = t);
    TokenData keyBackupCurrentToken = viewModel.getKeyBackupCurrentToken();
    if (keyBackupCurrentToken != null) {
        int triesRemaining = keyBackupCurrentToken.getTriesRemaining();
        if (triesRemaining <= 3) {
            int daysRemaining = getLockoutDays(timeRemaining);
            new MaterialAlertDialogBuilder(requireContext()).setTitle(R.string.RegistrationLockFragment__not_many_tries_left).setMessage(getTriesRemainingDialogMessage(triesRemaining, daysRemaining)).setPositiveButton(android.R.string.ok, null).setNeutralButton(R.string.PinRestoreEntryFragment_contact_support, (dialog, which) -> sendEmailToSupport()).show();
        }
        if (triesRemaining < 5) {
            errorLabel.setText(requireContext().getResources().getQuantityString(R.plurals.RegistrationLockFragment__d_attempts_remaining, triesRemaining, triesRemaining));
        }
    }
}
Also used : CircularProgressButtonUtil.setSpinning(org.thoughtcrime.securesms.util.CircularProgressButtonUtil.setSpinning) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) LifecycleDisposable(org.thoughtcrime.securesms.util.LifecycleDisposable) MaterialAlertDialogBuilder(com.google.android.material.dialog.MaterialAlertDialogBuilder) ViewUtil(org.thoughtcrime.securesms.util.ViewUtil) R(org.thoughtcrime.securesms.R) Toast(android.widget.Toast) View(android.view.View) ServiceUtil(org.thoughtcrime.securesms.util.ServiceUtil) CircularProgressButton(com.dd.CircularProgressButton) CircularProgressButtonUtil.cancelSpinning(org.thoughtcrime.securesms.util.CircularProgressButtonUtil.cancelSpinning) PinKeyboardType(org.thoughtcrime.securesms.lock.v2.PinKeyboardType) RegistrationViewDelegate.setDebugLogSubmitMultiTapView(org.thoughtcrime.securesms.registration.fragments.RegistrationViewDelegate.setDebugLogSubmitMultiTapView) InputType(android.text.InputType) BaseRegistrationViewModel(org.thoughtcrime.securesms.registration.viewmodel.BaseRegistrationViewModel) CallSuper(androidx.annotation.CallSuper) TokenData(org.thoughtcrime.securesms.pin.TokenData) TimeUnit(java.util.concurrent.TimeUnit) Log(org.signal.core.util.logging.Log) AndroidSchedulers(io.reactivex.rxjava3.android.schedulers.AndroidSchedulers) StringRes(androidx.annotation.StringRes) TextView(android.widget.TextView) Nullable(androidx.annotation.Nullable) Disposable(io.reactivex.rxjava3.disposables.Disposable) LoggingFragment(org.thoughtcrime.securesms.LoggingFragment) EditorInfo(android.view.inputmethod.EditorInfo) EditText(android.widget.EditText) Resources(android.content.res.Resources) PinKeyboardType(org.thoughtcrime.securesms.lock.v2.PinKeyboardType) TokenData(org.thoughtcrime.securesms.pin.TokenData) MaterialAlertDialogBuilder(com.google.android.material.dialog.MaterialAlertDialogBuilder) CallSuper(androidx.annotation.CallSuper)

Example 3 with NonNull

use of io.reactivex.rxjava3.annotations.NonNull in project Signal-Android by WhisperSystems.

the class EnterPhoneNumberFragment method requestVerificationCode.

private void requestVerificationCode(@NonNull Mode mode) {
    NavController navController = NavHostFragment.findNavController(this);
    Disposable request = viewModel.requestVerificationCode(mode).doOnSubscribe(unused -> SignalStore.account().setRegistered(false)).observeOn(AndroidSchedulers.mainThread()).subscribe(processor -> {
        if (processor.hasResult()) {
            SafeNavigation.safeNavigate(navController, EnterPhoneNumberFragmentDirections.actionEnterVerificationCode());
        } else if (processor.localRateLimit()) {
            Log.i(TAG, "Unable to request sms code due to local rate limit");
            SafeNavigation.safeNavigate(navController, EnterPhoneNumberFragmentDirections.actionEnterVerificationCode());
        } else if (processor.captchaRequired()) {
            Log.i(TAG, "Unable to request sms code due to captcha required");
            SafeNavigation.safeNavigate(navController, EnterPhoneNumberFragmentDirections.actionRequestCaptcha());
        } else if (processor.rateLimit()) {
            Log.i(TAG, "Unable to request sms code due to rate limit");
            Toast.makeText(register.getContext(), R.string.RegistrationActivity_rate_limited_to_service, Toast.LENGTH_LONG).show();
        } else if (processor.isImpossibleNumber()) {
            Log.w(TAG, "Impossible number", processor.getError());
            Dialogs.showAlertDialog(requireContext(), getString(R.string.RegistrationActivity_invalid_number), String.format(getString(R.string.RegistrationActivity_the_number_you_specified_s_is_invalid), viewModel.getNumber().getFullFormattedNumber()));
        } else if (processor.isNonNormalizedNumber()) {
            handleNonNormalizedNumberError(processor.getOriginalNumber(), processor.getNormalizedNumber(), mode);
        } else {
            Log.i(TAG, "Unknown error during verification code request", processor.getError());
            Toast.makeText(register.getContext(), R.string.RegistrationActivity_unable_to_connect_to_service, Toast.LENGTH_LONG).show();
        }
        cancelSpinning(register);
        enableAllEntries();
    });
    disposables.add(request);
}
Also used : LifecycleDisposable(org.thoughtcrime.securesms.util.LifecycleDisposable) Disposable(io.reactivex.rxjava3.disposables.Disposable) NavController(androidx.navigation.NavController)

Example 4 with NonNull

use of io.reactivex.rxjava3.annotations.NonNull in project Signal-Android by WhisperSystems.

the class DirectoryHelper method refreshNumbers.

@WorkerThread
private static void refreshNumbers(@NonNull Context context, @NonNull Set<String> databaseNumbers, @NonNull Set<String> systemNumbers, boolean notifyOfNewUsers, boolean removeSystemContactEntryForMissing) throws IOException {
    RecipientDatabase recipientDatabase = SignalDatabase.recipients();
    Set<String> allNumbers = SetUtil.union(databaseNumbers, systemNumbers);
    if (allNumbers.isEmpty()) {
        Log.w(TAG, "No numbers to refresh!");
        return;
    }
    Stopwatch stopwatch = new Stopwatch("refresh");
    DirectoryResult result;
    if (FeatureFlags.cdsh()) {
        result = ContactDiscoveryV3.getDirectoryResult(databaseNumbers, systemNumbers);
    } else {
        result = ContactDiscoveryV2.getDirectoryResult(context, databaseNumbers, systemNumbers);
    }
    stopwatch.split("network");
    if (result.getNumberRewrites().size() > 0) {
        Log.i(TAG, "[getDirectoryResult] Need to rewrite some numbers.");
        recipientDatabase.updatePhoneNumbers(result.getNumberRewrites());
    }
    Map<RecipientId, ACI> aciMap = recipientDatabase.bulkProcessCdsResult(result.getRegisteredNumbers());
    Set<String> activeNumbers = result.getRegisteredNumbers().keySet();
    Set<RecipientId> activeIds = aciMap.keySet();
    Set<RecipientId> inactiveIds = Stream.of(allNumbers).filterNot(activeNumbers::contains).filterNot(n -> result.getNumberRewrites().containsKey(n)).filterNot(n -> result.getIgnoredNumbers().contains(n)).map(recipientDatabase::getOrInsertFromE164).collect(Collectors.toSet());
    stopwatch.split("process-cds");
    UnlistedResult unlistedResult = filterForUnlistedUsers(context, inactiveIds);
    inactiveIds.removeAll(unlistedResult.getPossiblyActive());
    if (unlistedResult.getRetries().size() > 0) {
        Log.i(TAG, "Some profile fetches failed to resolve. Assuming not-inactive for now and scheduling a retry.");
        RetrieveProfileJob.enqueue(unlistedResult.getRetries());
    }
    stopwatch.split("handle-unlisted");
    Set<RecipientId> preExistingRegisteredUsers = new HashSet<>(recipientDatabase.getRegistered());
    recipientDatabase.bulkUpdatedRegisteredStatus(aciMap, inactiveIds);
    stopwatch.split("update-registered");
    updateContactsDatabase(context, activeIds, removeSystemContactEntryForMissing, result.getNumberRewrites());
    stopwatch.split("contacts-db");
    if (TextSecurePreferences.isMultiDevice(context)) {
        ApplicationDependencies.getJobManager().add(new MultiDeviceContactUpdateJob());
    }
    if (TextSecurePreferences.hasSuccessfullyRetrievedDirectory(context) && notifyOfNewUsers) {
        Set<RecipientId> systemContacts = new HashSet<>(recipientDatabase.getSystemContacts());
        Set<RecipientId> newlyRegisteredSystemContacts = new HashSet<>(activeIds);
        newlyRegisteredSystemContacts.removeAll(preExistingRegisteredUsers);
        newlyRegisteredSystemContacts.retainAll(systemContacts);
        notifyNewUsers(context, newlyRegisteredSystemContacts);
    } else {
        TextSecurePreferences.setHasSuccessfullyRetrievedDirectory(context, true);
    }
    stopwatch.stop(TAG);
}
Also used : SignalStore(org.thoughtcrime.securesms.keyvalue.SignalStore) NonNull(androidx.annotation.NonNull) R(org.thoughtcrime.securesms.R) SignalServiceAddress(org.whispersystems.signalservice.api.push.SignalServiceAddress) Manifest(android.Manifest) ProfileAndCredential(org.whispersystems.signalservice.api.profiles.ProfileAndCredential) ContactsContract(android.provider.ContactsContract) BulkOperationsHandle(org.thoughtcrime.securesms.database.RecipientDatabase.BulkOperationsHandle) RegisteredState(org.thoughtcrime.securesms.database.RecipientDatabase.RegisteredState) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) StorageSyncHelper(org.thoughtcrime.securesms.storage.StorageSyncHelper) ContentResolver(android.content.ContentResolver) Map(java.util.Map) SignalProtocolAddress(org.whispersystems.libsignal.SignalProtocolAddress) Recipient(org.thoughtcrime.securesms.recipients.Recipient) AccountManager(android.accounts.AccountManager) ACI(org.whispersystems.signalservice.api.push.ACI) Account(android.accounts.Account) ApplicationDependencies(org.thoughtcrime.securesms.dependencies.ApplicationDependencies) Collection(java.util.Collection) Set(java.util.Set) SetUtil(org.thoughtcrime.securesms.util.SetUtil) Objects(java.util.Objects) Log(org.signal.core.util.logging.Log) FeatureFlags(org.thoughtcrime.securesms.util.FeatureFlags) List(java.util.List) Nullable(androidx.annotation.Nullable) StorageSyncJob(org.thoughtcrime.securesms.jobs.StorageSyncJob) ProfileService(org.whispersystems.signalservice.api.services.ProfileService) BuildConfig(org.thoughtcrime.securesms.BuildConfig) InsertResult(org.thoughtcrime.securesms.database.MessageDatabase.InsertResult) Context(android.content.Context) SignalDatabase(org.thoughtcrime.securesms.database.SignalDatabase) Stream(com.annimon.stream.Stream) Util(org.thoughtcrime.securesms.util.Util) WorkerThread(androidx.annotation.WorkerThread) RemoteException(android.os.RemoteException) RetrieveProfileJob(org.thoughtcrime.securesms.jobs.RetrieveProfileJob) RecipientDatabase(org.thoughtcrime.securesms.database.RecipientDatabase) SignalServiceProfile(org.whispersystems.signalservice.api.profiles.SignalServiceProfile) TextSecurePreferences(org.thoughtcrime.securesms.util.TextSecurePreferences) HashSet(java.util.HashSet) Schedulers(io.reactivex.rxjava3.schedulers.Schedulers) Pair(org.whispersystems.libsignal.util.Pair) NotificationChannels(org.thoughtcrime.securesms.notifications.NotificationChannels) ProfileUtil(org.thoughtcrime.securesms.util.ProfileUtil) Calendar(java.util.Calendar) Observable(io.reactivex.rxjava3.core.Observable) RegistrationUtil(org.thoughtcrime.securesms.registration.RegistrationUtil) ContactsDatabase(org.thoughtcrime.securesms.contacts.ContactsDatabase) MultiDeviceContactUpdateJob(org.thoughtcrime.securesms.jobs.MultiDeviceContactUpdateJob) Cursor(android.database.Cursor) Collectors(com.annimon.stream.Collectors) Permissions(org.thoughtcrime.securesms.permissions.Permissions) UuidUtil(org.whispersystems.signalservice.api.util.UuidUtil) TextUtils(android.text.TextUtils) IOException(java.io.IOException) ServiceResponse(org.whispersystems.signalservice.internal.ServiceResponse) OperationApplicationException(android.content.OperationApplicationException) Optional(org.whispersystems.libsignal.util.guava.Optional) TimeUnit(java.util.concurrent.TimeUnit) CursorUtil(org.thoughtcrime.securesms.util.CursorUtil) IncomingJoinedMessage(org.thoughtcrime.securesms.sms.IncomingJoinedMessage) ContactAccessor(org.thoughtcrime.securesms.contacts.ContactAccessor) Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) PhoneNumberFormatter(org.thoughtcrime.securesms.phonenumbers.PhoneNumberFormatter) Collections(java.util.Collections) RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) ACI(org.whispersystems.signalservice.api.push.ACI) Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) RecipientDatabase(org.thoughtcrime.securesms.database.RecipientDatabase) MultiDeviceContactUpdateJob(org.thoughtcrime.securesms.jobs.MultiDeviceContactUpdateJob) HashSet(java.util.HashSet) WorkerThread(androidx.annotation.WorkerThread)

Example 5 with NonNull

use of io.reactivex.rxjava3.annotations.NonNull in project RxJava by ReactiveX.

the class FlowableFromStreamTest method requestRaceBase.

void requestRaceBase(boolean conditional) throws Exception {
    ExecutorService exec = Executors.newCachedThreadPool();
    try {
        for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) {
            AtomicInteger counter = new AtomicInteger();
            int max = 100;
            Flowable<Integer> source = Flowable.fromStream(IntStream.rangeClosed(1, max).boxed());
            if (conditional) {
                source = source.filter(v -> true);
            }
            CountDownLatch cdl = new CountDownLatch(1);
            source.subscribe(new FlowableSubscriber<Integer>() {

                @NonNull
                Subscription upstream;

                @Override
                public void onSubscribe(@NonNull Subscription s) {
                    this.upstream = s;
                    s.request(1);
                }

                @Override
                public void onNext(Integer t) {
                    counter.getAndIncrement();
                    AtomicInteger sync = new AtomicInteger(2);
                    exec.submit(() -> {
                        if (sync.decrementAndGet() != 0) {
                            while (sync.get() != 0) {
                            }
                        }
                        upstream.request(1);
                    });
                    if (sync.decrementAndGet() != 0) {
                        while (sync.get() != 0) {
                        }
                    }
                }

                @Override
                public void onError(Throwable t) {
                    t.printStackTrace();
                    cdl.countDown();
                }

                @Override
                public void onComplete() {
                    counter.getAndIncrement();
                    cdl.countDown();
                }
            });
            assertTrue(cdl.await(60, TimeUnit.SECONDS));
            assertEquals(max + 1, counter.get());
        }
    } finally {
        exec.shutdown();
    }
}
Also used : SimpleQueue(io.reactivex.rxjava3.operators.SimpleQueue) java.util(java.util) TestException(io.reactivex.rxjava3.exceptions.TestException) java.util.concurrent(java.util.concurrent) java.util.stream(java.util.stream) java.util.concurrent.atomic(java.util.concurrent.atomic) Test(org.junit.Test) NonNull(io.reactivex.rxjava3.annotations.NonNull) Schedulers(io.reactivex.rxjava3.schedulers.Schedulers) QueueFuseable(io.reactivex.rxjava3.operators.QueueFuseable) Subscription(org.reactivestreams.Subscription) io.reactivex.rxjava3.core(io.reactivex.rxjava3.core) Assert(org.junit.Assert) QueueSubscription(io.reactivex.rxjava3.operators.QueueSubscription) io.reactivex.rxjava3.testsupport(io.reactivex.rxjava3.testsupport) NonNull(io.reactivex.rxjava3.annotations.NonNull) Subscription(org.reactivestreams.Subscription) QueueSubscription(io.reactivex.rxjava3.operators.QueueSubscription)

Aggregations

Test (org.junit.Test)20 Disposable (io.reactivex.rxjava3.disposables.Disposable)17 IOException (java.io.IOException)11 NonNull (io.reactivex.rxjava3.annotations.NonNull)10 InOrder (org.mockito.InOrder)10 TestException (io.reactivex.rxjava3.exceptions.TestException)9 io.reactivex.rxjava3.core (io.reactivex.rxjava3.core)7 TimeUnit (java.util.concurrent.TimeUnit)6 Assert (org.junit.Assert)6 NonNull (androidx.annotation.NonNull)5 Nullable (androidx.annotation.Nullable)5 Schedulers (io.reactivex.rxjava3.schedulers.Schedulers)5 java.util.stream (java.util.stream)5 BooleanSubscription (io.reactivex.rxjava3.internal.subscriptions.BooleanSubscription)4 QueueFuseable (io.reactivex.rxjava3.operators.QueueFuseable)4 QueueSubscription (io.reactivex.rxjava3.operators.QueueSubscription)4 io.reactivex.rxjava3.testsupport (io.reactivex.rxjava3.testsupport)4 Iterator (java.util.Iterator)4 Objects (java.util.Objects)4 Subscription (org.reactivestreams.Subscription)4