Java 类android.arch.lifecycle.Observer 实例源码

项目:mapbox-plugins-android    文件:LiveDataTestUtil.java   
/**
 * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds.
 * Once we got a notification via onChanged, we stop observing.
 */
public static <T> T getValue(final LiveData<T> liveData) throws InterruptedException {
  final Object[] data = new Object[1];
  final CountDownLatch latch = new CountDownLatch(1);
  Observer<T> observer = new Observer<T>() {
    @Override
    public void onChanged(@Nullable T o) {
      data[0] = o;
      latch.countDown();
      liveData.removeObserver(this);
    }
  };
  liveData.observeForever(observer);
  latch.await(2, TimeUnit.SECONDS);
  //noinspection unchecked
  return (T) data[0];
}
项目:CleanArchitechture    文件:TeamMvvmFragment.java   
@Override
public void initData(Bundle savedInstanceState) {
    mViewDataBinding.rvTeam.addItemDecoration(new DividerItemDecoration(getThis(), DividerItemDecoration.VERTICAL));
    mViewDataBinding.rvTeam.setAdapter(mAdapter);
    if (getArguments() != null) {
        int seasion = getArguments().getInt("Seasion ID");
        mSeasionName = getArguments().getString("Seasion Name");
        mViewModel.getResults(seasion).observe(this, new Observer<Resource<List<TeamModel>>>() {
            @Override
            public void onChanged(@Nullable Resource<List<TeamModel>> listResource) {
                mViewDataBinding.setResource(listResource);
                mViewDataBinding.executePendingBindings();
                if (listResource != null && listResource.data != null) {
                    mAdapter.updateData(listResource.data);
                }
            }
        });
    }

}
项目:RoomDagger2Demo    文件:MainActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DaggerAppComponent.builder()
            .appModule(new AppModule(getApplication()))
            .roomModule(new RoomModule(getApplication()))
            .build()
            .inject(this);


    productRepository.findAll().observe(this, new Observer<List<Product>>() {
        @Override
        public void onChanged(@Nullable List<Product> products) {
            Toast.makeText(MainActivity.this, String.format("Product size: %s", products.size()), Toast.LENGTH_SHORT).show();
        }
    });
}
项目:AndroidArchitectureComponets    文件:ViewHolderActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_holder);
    tvUsername = findViewById(R.id.tv_username);
    tvAddress = findViewById(R.id.tv_address);

    mDemoViewHolder = ViewModelProviders.of(this).get(DemoViewHolder.class);

    mDemoViewHolder.getUserInfo().observe(this, new Observer<UserEntity>() {
        @Override
        public void onChanged(@Nullable UserEntity userEntity) {
            if (userEntity == null) {
                return;
            }
            tvUsername.setText(userEntity.getUsername());
            tvAddress.setText(userEntity.getAddress());
        }
    });
}
项目:GSoC-Info-Android    文件:OrganizationFragment.java   
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_org, container, false);
    RecyclerView recyclerView = view.findViewById(R.id.rv_org);
    DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
    float width = displayMetrics.widthPixels / displayMetrics.density;
    final int spanCount = (int) (width / 180.00);
    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));
    orgAdapter = new OrgAdapter();
    recyclerView.setAdapter(orgAdapter);
    organizationViewModel = ViewModelProviders.of(getActivity()).get(OrganizationViewModel.class);
    setHasOptionsMenu(true);
    organizationViewModel.getOrganizations().observe(this, new Observer<PagedList<Organization>>() {
        @Override
        public void onChanged(@Nullable PagedList<Organization> organizations) {
            orgPagedList = organizations;
            orgAdapter.setList(orgPagedList);
            view.findViewById(R.id.progressBar).setVisibility(View.GONE);
        }
    });

    return view;
}
项目:AndroidArchitectureComponets    文件:LiveDataActivity.java   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_live_data);

    tvUsername = findViewById(R.id.tv_username);

    username = new MutableLiveData<>();

    username.observe(this, new Observer<String>() {
        @Override
        public void onChanged(@Nullable String s) {
            tvUsername.setText(s);
        }
    });
}
项目:Hands-On-Android-UI-Development    文件:ClaimItemAdapter.java   
public ClaimItemAdapter(
        final Context context,
        final LifecycleOwner owner,
        final LiveData<List<ClaimItem>> liveItems) {

    this.layoutInflater = LayoutInflater.from(context);
    this.itemPresenter = new ItemPresenter(context);

    liveItems.observe(owner, new Observer<List<ClaimItem>>() {
        @Override
        public void onChanged(final List<ClaimItem> claimItems) {
            if (!items.isEmpty()) {
                updateCommand.exec(Pair.create(items, claimItems));
            } else {
                createDisplayListCommand.exec(claimItems);
            }
        }
    });
}
项目:Hands-On-Android-UI-Development    文件:ClaimItemAdapter.java   
public ClaimItemAdapter(
        final Context context,
        final LifecycleOwner owner,
        final LiveData<List<ClaimItem>> liveItems) {

    this.layoutInflater = LayoutInflater.from(context);
    this.itemPresenter = new ItemPresenter(context);

    liveItems.observe(owner, new Observer<List<ClaimItem>>() {
        public void onChanged(final List<ClaimItem> claimItems) {
            ClaimItemAdapter.this.items = (claimItems != null)
                    ? claimItems
                    : Collections.<ClaimItem>emptyList();

            ClaimItemAdapter.this.notifyDataSetChanged();
        }
    });
}
项目:Hands-On-Android-UI-Development    文件:AllowanceOverviewPresenter.java   
public AllowanceOverviewPresenter(
        final LifecycleOwner lifecycleOwner,
        final int allowance) {

    ClaimApplication.getClaimDatabase()
            .claimItemDao()
            .selectAll()
            .observe(lifecycleOwner, new Observer<List<ClaimItem>>() {
                @Override
                public void onChanged(final List<ClaimItem> claimItems) {
                    updateSpendStatsCommand.exec(claimItems);
                }
            });

    this.allowance.set(allowance);
}
项目:Hands-On-Android-UI-Development    文件:ClaimItemAdapter.java   
public ClaimItemAdapter(
        final Context context,
        final LifecycleOwner owner,
        final LiveData<List<ClaimItem>> liveItems) {

    this.layoutInflater = LayoutInflater.from(context);
    this.itemPresenter = new ItemPresenter(context);

    liveItems.observe(owner, new Observer<List<ClaimItem>>() {
        public void onChanged(final List<ClaimItem> claimItems) {
            ClaimItemAdapter.this.items = (claimItems != null)
                    ? claimItems
                    : Collections.<ClaimItem>emptyList();

            ClaimItemAdapter.this.notifyDataSetChanged();
        }
    });
}
项目:Hands-On-Android-UI-Development    文件:AllowanceOverviewPresenter.java   
public AllowanceOverviewPresenter(
        final LifecycleOwner lifecycleOwner,
        final int allowance) {

    ClaimApplication.getClaimDatabase()
            .claimItemDao()
            .selectAll()
            .observe(lifecycleOwner, new Observer<List<ClaimItem>>() {
                @Override
                public void onChanged(final List<ClaimItem> claimItems) {
                    updateSpendStatsCommand.exec(claimItems);
                }
            });

    this.allowance.set(allowance);
}
项目:mvvm-template    文件:LiveDataTestUtil.java   
public static <T> T getValue(LiveData<T> liveData) throws InterruptedException {
    final Object[] data = new Object[1];
    CountDownLatch latch = new CountDownLatch(1);
    Observer<T> observer = new Observer<T>() {
        @Override
        public void onChanged(@Nullable T o) {
            data[0] = o;
            latch.countDown();
            liveData.removeObserver(this);
        }
    };
    liveData.observeForever(observer);
    latch.await(2, TimeUnit.SECONDS);
    //noinspection unchecked
    return (T) data[0];
}
项目:mapbox-plugins-android    文件:PlaceAutocompleteFragment.java   
private void subscribe() {
  viewModel.geocodingLiveData.observe(this, new Observer<GeocodingResponse>() {
    @Override
    public void onChanged(@Nullable GeocodingResponse geocodingResponse) {
      updateSearchResultView(geocodingResponse);
    }
  });

  // Subscribe to the search history database
  DataRepository.getInstance(viewModel.getDatabase()).getSearchHistory().observe(this,
    new Observer<List<SearchHistoryEntity>>() {
      @Override
      public void onChanged(@Nullable List<SearchHistoryEntity> searchHistoryEntities) {
        updateSearchHistoryView(searchHistoryEntities);
      }
    });
}
项目:CricKotlin    文件:NetworkBoundResourceTest.java   
@Test
public void basicFromNetwork() {
    AtomicReference<Foo> saved = new AtomicReference<>();
    shouldFetch = Objects::isNull;
    Foo fetchedDbValue = new Foo(1);
    saveCallResult = foo -> {
        saved.set(foo);
        dbData.setValue(fetchedDbValue);
        return null;
    };
    final Foo networkResult = new Foo(1);
    createCall = (aVoid) -> ApiUtil.createCall(Response.success(networkResult));

    Observer<Resource<Foo>> observer = Mockito.mock(Observer.class);
    networkBoundResource.asLiveData().observeForever(observer);
    drain();
    verify(observer).onChanged(Resource.loading(null));
    reset(observer);
    dbData.setValue(null);
    drain();
    assertThat(saved.get(), is(networkResult));
    verify(observer).onChanged(Resource.success(fetchedDbValue));
}
项目:CricKotlin    文件:NetworkBoundResourceTest.java   
@Test
public void failureFromNetwork() {
    AtomicBoolean saved = new AtomicBoolean(false);
    shouldFetch = Objects::isNull;
    saveCallResult = foo -> {
        saved.set(true);
        return null;
    };
    ResponseBody body = ResponseBody.create(MediaType.parse("text/html"), "error");
    createCall = (aVoid) -> ApiUtil.createCall(Response.error(500, body));

    Observer<Resource<Foo>> observer = Mockito.mock(Observer.class);
    networkBoundResource.asLiveData().observeForever(observer);
    drain();
    verify(observer).onChanged(Resource.loading(null));
    reset(observer);
    dbData.setValue(null);
    drain();
    assertThat(saved.get(), is(false));
    verify(observer).onChanged(Resource.error("error", null));
    verifyNoMoreInteractions(observer);
}
项目:CricKotlin    文件:NetworkBoundResourceTest.java   
@Test
public void dbSuccessWithoutNetwork() {
    AtomicBoolean saved = new AtomicBoolean(false);
    shouldFetch = Objects::isNull;
    saveCallResult = foo -> {
        saved.set(true);
        return null;
    };

    Observer<Resource<Foo>> observer = Mockito.mock(Observer.class);
    networkBoundResource.asLiveData().observeForever(observer);
    drain();
    verify(observer).onChanged(Resource.loading(null));
    reset(observer);
    Foo dbFoo = new Foo(1);
    dbData.setValue(dbFoo);
    drain();
    verify(observer).onChanged(Resource.success(dbFoo));
    assertThat(saved.get(), is(false));
    Foo dbFoo2 = new Foo(2);
    dbData.setValue(dbFoo2);
    drain();
    verify(observer).onChanged(Resource.success(dbFoo2));
    verifyNoMoreInteractions(observer);
}
项目:ProjectProgressTracker    文件:ProjectDetail.java   
private void loadProject(int pID) {
    projectsViewModel.findByID(pID).observe((LifecycleOwner) this, new Observer<Project>() {
        @Override
        public void onChanged(@Nullable Project project) {
            getSupportActionBar().setTitle(project.getTitle());
            getSupportActionBar().setSubtitle(project.getDesc());
            thisprojecta = project;
            edit_title.setText(project.getTitle());
            edit_desc.setText(project.getDesc());
            edit_priority.setProgress(project.getPriority());
            deadline = project.getDead_line();
            if(deadline != null)
                edit_deadline.setText(project.getDead_line().toString());
        }
    });
}
项目:ProjectProgressTracker    文件:TodoFeedFragment.java   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v  = inflater.inflate(R.layout.fragment_todo_feed, container, false);
    recyclerView = v.findViewById(R.id.recyclerView);
    recyclerViewAdapter = new RecyclerViewAdapter<Todo>(new ArrayList<Todo>(),this, this);
    recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity().getBaseContext()));

    recyclerView.setAdapter(recyclerViewAdapter);
    viewModel = ViewModelProviders.of(this).get(todosViewModel.class);
    viewModel.getAll().observe((LifecycleOwner) getActivity(), new Observer<List<Todo>>() {
        @Override
        public void onChanged(@Nullable List<Todo> todos) {
            recyclerViewAdapter.addItems(todos);
        }
    });
    return v;
}
项目:firebase-chat-android-architecture-components    文件:NetworkBoundResourceTest.java   
@Test
public void basicFromNetwork() {
    AtomicReference<Foo> saved = new AtomicReference<>();
    shouldFetch = Objects::isNull;
    Foo fetchedDbValue = new Foo(1);
    saveCallResult = foo -> {
        saved.set(foo);
        dbData.setValue(fetchedDbValue);
        return null;
    };
    final Foo networkResult = new Foo(1);
    createCall = (aVoid) -> ApiUtil.createCall(Response.success(networkResult));

    Observer<Resource<Foo>> observer = Mockito.mock(Observer.class);
    networkBoundResource.asLiveData().observeForever(observer);
    drain();
    verify(observer).onChanged(Resource.loading(null));
    reset(observer);
    dbData.setValue(null);
    drain();
    assertThat(saved.get(), is(networkResult));
    verify(observer).onChanged(Resource.success(fetchedDbValue));
}
项目:firebase-chat-android-architecture-components    文件:NetworkBoundResourceTest.java   
@Test
public void dbSuccessWithoutNetwork() {
    AtomicBoolean saved = new AtomicBoolean(false);
    shouldFetch = Objects::isNull;
    saveCallResult = foo -> {
        saved.set(true);
        return null;
    };

    Observer<Resource<Foo>> observer = Mockito.mock(Observer.class);
    networkBoundResource.asLiveData().observeForever(observer);
    drain();
    verify(observer).onChanged(Resource.loading(null));
    reset(observer);
    Foo dbFoo = new Foo(1);
    dbData.setValue(dbFoo);
    drain();
    verify(observer).onChanged(Resource.success(dbFoo));
    assertThat(saved.get(), is(false));
    Foo dbFoo2 = new Foo(2);
    dbData.setValue(dbFoo2);
    drain();
    verify(observer).onChanged(Resource.success(dbFoo2));
    verifyNoMoreInteractions(observer);
}
项目:firebase-chat-android-architecture-components    文件:UserRepositoryTest.java   
@Test
public void goToNetwork() {
    MutableLiveData<User> dbData = new MutableLiveData<>();
    when(userDao.findByLogin("foo")).thenReturn(dbData);
    User user = TestUtil.createUser("foo");
    LiveData<ApiResponse<User>> call = ApiUtil.successCall(user);
    when(githubService.getUser("foo")).thenReturn(call);
    Observer<Resource<User>> observer = mock(Observer.class);

    repo.loadUser("foo").observeForever(observer);
    verify(githubService, never()).getUser("foo");
    MutableLiveData<User> updatedDbData = new MutableLiveData<>();
    when(userDao.findByLogin("foo")).thenReturn(updatedDbData);
    dbData.setValue(null);
    verify(githubService).getUser("foo");
}
项目:ProjectProgressTracker    文件:TodoDetail.java   
private void loadTodo(int tID) {
    todosViewModel.findByID(tID).observe((LifecycleOwner) this, new Observer<Todo>() {
        @Override
        public void onChanged(@Nullable Todo todo) {
            thistodo = todo;
            edit_title.setText(thistodo.getTitle());
            edit_desc.setText(thistodo.getDesc());
            edit_priority.setProgress(thistodo.getPriority());
            deadline = todo.getDeadline_date();
            if(deadline != null)
                edit_deadline.setText(todo.getDeadline_date().toString());
            edit_cost.setText(String.valueOf(thistodo.getCost()));
            edit_time.setText(String.valueOf(thistodo.getTime()));
            Log.w("projectID", String.valueOf(thistodo.getProject()));
            loadParentProject(todo.getProject());
        }
    });
}
项目:ProjectProgressTracker    文件:ProjectsFeedFragment.java   
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v  = inflater.inflate(R.layout.fragment_projects_feed, container, false);
    recyclerView = v.findViewById(R.id.recyclerView);
    recyclerViewAdapter = new RecyclerViewAdapter<Project>(new ArrayList<Project>(), this, this);
    recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity().getBaseContext()));
    recyclerView.setAdapter(recyclerViewAdapter);
    projectsViewModel = MainActivity.getProjectsViewModel();
    todosViewModel = MainActivity.getTodosViewModel();
    projectsViewModel.getAll().observe((LifecycleOwner) getActivity(), new Observer<List<Project>>() {
        @Override
        public void onChanged(@Nullable List<Project> projects) {
            recyclerViewAdapter.addItems(projects);
        }
    });
    return v;
}
项目:firebase-chat-android-architecture-components    文件:UserViewModelTest.java   
@Test
public void sendResultToUI() {
    MutableLiveData<Resource<User>> foo = new MutableLiveData<>();
    MutableLiveData<Resource<User>> bar = new MutableLiveData<>();
    when(userRepository.loadUser("foo")).thenReturn(foo);
    when(userRepository.loadUser("bar")).thenReturn(bar);
    Observer<Resource<User>> observer = mock(Observer.class);
    userViewModel.getUser().observeForever(observer);
    userViewModel.setLogin("foo");
    verify(observer, never()).onChanged(any(Resource.class));
    User fooUser = TestUtil.createUser("foo");
    Resource<User> fooValue = Resource.success(fooUser);

    foo.setValue(fooValue);
    verify(observer).onChanged(fooValue);
    reset(observer);
    User barUser = TestUtil.createUser("bar");
    Resource<User> barValue = Resource.success(barUser);
    bar.setValue(barValue);
    userViewModel.setLogin("bar");
    verify(observer).onChanged(barValue);
}
项目:firebase-chat-android-architecture-components    文件:UserViewModelTest.java   
@Test
public void retry() {
    userViewModel.setLogin("foo");
    verifyNoMoreInteractions(inboxRepository, userRepository);
    userViewModel.retry();
    verifyNoMoreInteractions(inboxRepository, userRepository);
    Observer userObserver = mock(Observer.class);
    userViewModel.getUser().observeForever(userObserver);
    Observer repoObserver = mock(Observer.class);
    userViewModel.getRepositories().observeForever(repoObserver);

    verify(userRepository).loadUser("foo");
    verify(inboxRepository).loadRepos("foo");
    reset(userRepository, inboxRepository);

    userViewModel.retry();
    verify(userRepository).loadUser("foo");
    verify(inboxRepository).loadRepos("foo");
    reset(userRepository, inboxRepository);
    userViewModel.getUser().removeObserver(userObserver);
    userViewModel.getRepositories().removeObserver(repoObserver);

    userViewModel.retry();
    verifyNoMoreInteractions(userRepository, inboxRepository);
}
项目:RoomDemo2017    文件:ListFragment.java   
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Set up and subscribe (observe) to the ViewModel
    listItemCollectionViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(ListItemCollectionViewModel.class);

    listItemCollectionViewModel.getListItems().observe(this, new Observer<List<ListItem>>() {
        @Override
        public void onChanged(@Nullable List<ListItem> listItems) {
            if (ListFragment.this.listOfData == null) {
                setListData(listItems);
            }
        }
    });

}
项目:RoomDemo2017    文件:DetailFragment.java   
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Set up and subscribe (observe) to the ViewModel
    listItemViewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(ListItemViewModel.class);

    listItemViewModel.getListItemById(itemId).observe(this, new Observer<ListItem>() {
        @Override
        public void onChanged(@Nullable ListItem listItem) {
            if (listItem != null) {
                dateAndTime.setText(listItem.getItemId());
                message.setText(listItem.getMessage());
                coloredBackground.setImageResource(listItem.getColorResource());
            }

        }
    });


}
项目:android-architecture-components    文件:LiveDataTestUtil.java   
public static <T> T getValue(LiveData<T> liveData) throws InterruptedException {
    final Object[] data = new Object[1];
    CountDownLatch latch = new CountDownLatch(1);
    Observer<T> observer = new Observer<T>() {
        @Override
        public void onChanged(@Nullable T o) {
            data[0] = o;
            latch.countDown();
            liveData.removeObserver(this);
        }
    };
    liveData.observeForever(observer);
    latch.await(2, TimeUnit.SECONDS);
    //noinspection unchecked
    return (T) data[0];
}
项目:android-room-with-a-view    文件:LiveDataTestUtil.java   
/**
 * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds.
 * Once we got a notification via onChanged, we stop observing.
 */
public static <T> T getValue(final LiveData<T> liveData) throws InterruptedException {
    final Object[] data = new Object[1];
    final CountDownLatch latch = new CountDownLatch(1);
    Observer<T> observer = new Observer<T>() {
        @Override
        public void onChanged(@Nullable T o) {
            data[0] = o;
            latch.countDown();
            liveData.removeObserver(this);
        }
    };
    liveData.observeForever(observer);
    latch.await(2, TimeUnit.SECONDS);
    //noinspection unchecked
    return (T) data[0];
}
项目:android-architecture-components    文件:NetworkBoundResourceTest.java   
@Test
public void failureFromNetwork() {
    AtomicBoolean saved = new AtomicBoolean(false);
    shouldFetch = Objects::isNull;
    saveCallResult = foo -> {
        saved.set(true);
        return null;
    };
    ResponseBody body = ResponseBody.create(MediaType.parse("text/html"), "error");
    createCall = (aVoid) -> ApiUtil.createCall(Response.error(500, body));

    Observer<Resource<Foo>> observer = Mockito.mock(Observer.class);
    networkBoundResource.asLiveData().observeForever(observer);
    drain();
    verify(observer).onChanged(Resource.loading(null));
    reset(observer);
    dbData.setValue(null);
    drain();
    assertThat(saved.get(), is(false));
    verify(observer).onChanged(Resource.error("error", null));
    verifyNoMoreInteractions(observer);
}
项目:android-architecture-components    文件:NetworkBoundResourceTest.java   
@Test
public void dbSuccessWithoutNetwork() {
    AtomicBoolean saved = new AtomicBoolean(false);
    shouldFetch = Objects::isNull;
    saveCallResult = foo -> {
        saved.set(true);
        return null;
    };

    Observer<Resource<Foo>> observer = Mockito.mock(Observer.class);
    networkBoundResource.asLiveData().observeForever(observer);
    drain();
    verify(observer).onChanged(Resource.loading(null));
    reset(observer);
    Foo dbFoo = new Foo(1);
    dbData.setValue(dbFoo);
    drain();
    verify(observer).onChanged(Resource.success(dbFoo));
    assertThat(saved.get(), is(false));
    Foo dbFoo2 = new Foo(2);
    dbData.setValue(dbFoo2);
    drain();
    verify(observer).onChanged(Resource.success(dbFoo2));
    verifyNoMoreInteractions(observer);
}
项目:igrow-android    文件:SingleLiveEvent.java   
@MainThread
public void observe(LifecycleOwner owner, final Observer<T> observer) {

    if (hasActiveObservers()) {
        Log.w(TAG, "Multiple observers registered but only one will be notified of changes.");
    }

    // Observe the internal MutableLiveData
    super.observe(owner, new Observer<T>() {
        @Override
        public void onChanged(@Nullable T t) {
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(t);
            }
        }
    });
}
项目:android-architecture-components    文件:UserRepositoryTest.java   
@Test
public void goToNetwork() {
    MutableLiveData<User> dbData = new MutableLiveData<>();
    when(userDao.findByLogin("foo")).thenReturn(dbData);
    User user = TestUtil.createUser("foo");
    LiveData<ApiResponse<User>> call = ApiUtil.successCall(user);
    when(githubService.getUser("foo")).thenReturn(call);
    Observer<Resource<User>> observer = mock(Observer.class);

    repo.loadUser("foo").observeForever(observer);
    verify(githubService, never()).getUser("foo");
    MutableLiveData<User> updatedDbData = new MutableLiveData<>();
    when(userDao.findByLogin("foo")).thenReturn(updatedDbData);
    dbData.setValue(null);
    verify(githubService).getUser("foo");
}
项目:android-architecture-components    文件:RepoRepositoryTest.java   
@Test
public void search_fromDb() {
    List<Integer> ids = Arrays.asList(1, 2);

    Observer<Resource<List<Repo>>> observer = mock(Observer.class);
    MutableLiveData<RepoSearchResult> dbSearchResult = new MutableLiveData<>();
    MutableLiveData<List<Repo>> repositories = new MutableLiveData<>();

    when(dao.search("foo")).thenReturn(dbSearchResult);

    repository.search("foo").observeForever(observer);

    verify(observer).onChanged(Resource.loading(null));
    verifyNoMoreInteractions(service);
    reset(observer);

    RepoSearchResult dbResult = new RepoSearchResult("foo", ids, 2, null);
    when(dao.loadOrdered(ids)).thenReturn(repositories);

    dbSearchResult.postValue(dbResult);

    List<Repo> repoList = new ArrayList<>();
    repositories.postValue(repoList);
    verify(observer).onChanged(Resource.success(repoList));
    verifyNoMoreInteractions(service);
}
项目:GSoC-Info-Android    文件:MainPageFragment.java   
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_about, container, false);
    RecyclerView recyclerView = view.findViewById(R.id.rv_timeline);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    MainPageViewModel mainPageViewModel = ViewModelProviders.of(getActivity()).get(MainPageViewModel.class);
    timelineAdapter = new TimelineAdapter();
    recyclerView.setAdapter(timelineAdapter);
    mainPageViewModel.getMainPageCopy().observe(this, new Observer<MainPage.Copy>() {
        @Override
        public void onChanged(@Nullable MainPage.Copy copy) {
            timelineAdapter.setData(copy);
        }
    });
    return view;
}
项目:android-architecture-components    文件:LiveDataTestUtil.java   
/**
 * Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds.
 * Once we got a notification via onChanged, we stop observing.
 */
public static <T> T getValue(final LiveData<T> liveData) throws InterruptedException {
    final Object[] data = new Object[1];
    final CountDownLatch latch = new CountDownLatch(1);
    Observer<T> observer = new Observer<T>() {
        @Override
        public void onChanged(@Nullable T o) {
            data[0] = o;
            latch.countDown();
            liveData.removeObserver(this);
        }
    };
    liveData.observeForever(observer);
    latch.await(2, TimeUnit.SECONDS);
    //noinspection unchecked
    return (T) data[0];
}
项目:android-architecture-components    文件:SearchViewModelTest.java   
@Test
public void swap() {
    LiveData<Resource<Boolean>> nextPage = new MutableLiveData<>();
    when(repository.searchNextPage("foo")).thenReturn(nextPage);

    Observer<Resource<List<Repo>>> result = mock(Observer.class);
    viewModel.getResults().observeForever(result);
    verifyNoMoreInteractions(repository);
    viewModel.setQuery("foo");
    verify(repository).search("foo");
    viewModel.loadNextPage();

    viewModel.getLoadMoreStatus().observeForever(mock(Observer.class));
    verify(repository).searchNextPage("foo");
    assertThat(nextPage.hasActiveObservers(), is(true));
    viewModel.setQuery("bar");
    assertThat(nextPage.hasActiveObservers(), is(false));
    verify(repository).search("bar");
    verify(repository, never()).searchNextPage("bar");
}
项目:android-architecture-components    文件:UserViewModelTest.java   
@Test
public void sendResultToUI() {
    MutableLiveData<Resource<User>> foo = new MutableLiveData<>();
    MutableLiveData<Resource<User>> bar = new MutableLiveData<>();
    when(userRepository.loadUser("foo")).thenReturn(foo);
    when(userRepository.loadUser("bar")).thenReturn(bar);
    Observer<Resource<User>> observer = mock(Observer.class);
    userViewModel.getUser().observeForever(observer);
    userViewModel.setLogin("foo");
    verify(observer, never()).onChanged(any(Resource.class));
    User fooUser = TestUtil.createUser("foo");
    Resource<User> fooValue = Resource.success(fooUser);

    foo.setValue(fooValue);
    verify(observer).onChanged(fooValue);
    reset(observer);
    User barUser = TestUtil.createUser("bar");
    Resource<User> barValue = Resource.success(barUser);
    bar.setValue(barValue);
    userViewModel.setLogin("bar");
    verify(observer).onChanged(barValue);
}